Tuesday, June 26, 2012

ASP.Net MVC: Controllers - Routing


In MVC, the URLs are treated as API. When a web client accesses a URL, the following processing takes place.

  1. MVC Routing engine receives a requested URL
  2. Finds the Controller associated with request URL
  3. Finds and execute the associated Action (Controller method) that performs the requested and returns an appropriate response
The way the routing engine performs the above processing done through specification of routes in Global.asax or xxxAreaRegistration.cs files.

routes.MapRoute(
  "Default",   // name of route
  "{controller}/{action}/{id}", // the URL is matched against this pattern
  new { controller = "Home",  // if any of the parts in pattern are missing ,
    action = "Index",                  // use these defaults
    id = string.Empty,
   startpage = UrlParameter.Optional     // this parameter may or may not be provided
}

For example, given a URL, Product/List, the routing engine will look for a Controller named Product and an Action (public method) on the Controller called List. The value of id will be default to string.Empty.
Multiple routes can be defined. However, the order in which these routes are specified is significant. As a general rule, more specific routes should be defined before more generic, greedy routes that match a large number of URLs.

The routing engine gives preference to physical files before applying the Controller routing logic. To override this behavior, the routing engine can instructed to ignore routes using the IgnoreRoutes method.

Accessing Route Data Values in Controller Methods

The following information is available in a Controller Action method.
RouteData.Values["controller"]
RouteData.Values["action"]
RouteData.Values["id"]