Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 and Rewrites

I'm writing an MVC3 application that will need to make use of URL rewriting in the form of http://[server]/[City]-[State]/[some term]/ .

As I understand it, MVC3 contains a routing engine that uses {controler}/{action}/{id} which is defined in the Global.asax file:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

    }

Traditionally (in a non-MVC app), I would use some URL rewriting flavor to decode a url such as http://www.myserver.com/City-State/somesearch/ to querystring parameters that look something like this: http://www.myserver.com/city=City&state=State&query=somesearch

Keep in mind that this request would be coming from http://www.myserver.com/Home

Can this can be accomplished without having to specify a controller... something like this:

routes.MapRoute(
            "Results",
            "{city}-{state}/{searchTerm}",
            new { controller = "Results", action = "Search" }
        );

... or is it really best to have the controller listed?

How do you handle this in an MVC3 environment?

Thanks.

like image 317
ElHaix Avatar asked May 31 '26 11:05

ElHaix


2 Answers

URL rewriting in asp.net MVC3:- you can write code for url rewriting in Global.asax file :-

       //Default url
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default",
            "", 
            new { controller = "Home", action = "Index", id = "" }
        );

      //others url rewriting you want

        RouteTable.Routes.MapRoute(null, "Search/{City_State}/{ID}", new { controller = "Home", action = "Search" });
like image 177
Ram Khumana Avatar answered Jun 03 '26 01:06

Ram Khumana


Check out these two answers:

  • ASP.NET MVC Routes: How to define custom route
  • Defining custom URL routes in ASP.Net MVC

Summary:

  • Specify custom routes before the default one.
  • Define specific routes before general as they may match both.
  • Default values are optional.
  • Specify default Controller and Action in the default parameter object.
like image 20
Bart Verkoeijen Avatar answered Jun 03 '26 02:06

Bart Verkoeijen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!