Routing in ASP.Net MVC

A route is a URL pattern. Routing is a pattern matching process that monitors the requests and determines what to do with each request.

Introduction to Routing

A route is a URL pattern. Routing is a pattern matching process that monitors the requests and determines what to do with each request. In other words we can say Routing is a mechanism for mapping requests within our MVC application. The Routing mechanism passes the request to the handler. A handler may be a physical path such as .aspx or may be a class capable of processing our request such as controller in MVC.

Routing is the first state of the MVC request life cycle. The Routing engine uses the route table for matching the incoming URL. We can register one or more URL patterns to the route table in the application start event (defined in the Global.asax file).

How Routing works

MVC-1.jpg

All requests to the ASP.NET MVC based application are first served by a URLRoutingModule object. URLRoutingModule is nothing but HTTPModule. This module parses the request. This Module contains all routes that are registered in the Global.asax file under the Application_Start event. URLRoutingModule searches and matches for the route defined in the URL. When matches are found it retrieves the Route handler (IRouteHandler) object for that route. This Route handler helps to find the HTTP handler (IHttpHandler) object for the current request.

How to define Routing

protected void Application_Start()

{

AreaRegistration.RegisterAllAreas();

RegisterRoutes(RouteTable.Routes);

}

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

);

}

In a MVC application, a route table must have at least one route definition. In the example code above, the route template named "Default" is added to the route table. The URL pattern for the route contains controller and action placeholders.

The HTTP handler (founded by URLRoutingModule) is of the MvcHandler type. The MvcHandler determines which controller to invoke (by just adding the "Controller" suffix) to the value of the parameter and searches for this class in the project that must be an implementation of the "System.Web.Mvc.IController" interface. MvcHandler receives the controller instance from the MVC Controller factory. This Controller is responsible for handling the further processing of the request.

The action value in the URL determines which action method to call. Matching the name found for the controller name and action name is case insensitive. If more than one match is found for an action method then the framework will select the action method that best matches the URL parameter with the action method argument.

Additional URL parameters are passed as arguments of a selected action method. The .NET MVC framework will evaluate the argument(s) of the available action methods and match them by name. Note this matching of parameter is not case sensitive. The .NET MVC framework will select the action method with a large number of matching parameters.

How URLs are matched to routes

Routing is responsible for handling the URL request. When Routing receives a request, it first matches the request to the route. Matching depends on the following conditions.

  • The Default value that is added in route table.
  • The order in which the route is added.
  • The constrains that are provided for the route
  • Physical path, whether routing path matches with it
  • Routing pattern that defines route.

We need to consider the above condition when we create or define routes. Route matching attempts to match a route from the first route to the last route in the route table (Route collection).

Situations in which the Routing does not apply to an URL are:

  • Routing is explicitly ignored for the URL pattern within the route table as in the following:

    public static void RegisterRoutes(RouteCollection routes)
    {
    routes.Ignore("{resource}.axd/{*pathInfo}");
    }
     
  • Routing does not request that map to any existing physical path on the web server.

ASP.NET Routing VS URL Rewriting

ASP.NET Routing and URL rewriting are different. URL rewriting processes that change incoming request (by changing the URL) before it sends the request to the web page. URL rewriting does not have any pattern or API (for creating a URL). ASP.NET Routing and URL rewriting can both be used to make SEO friendly URLs.

ASP.NET Routing URL Rewriting
The URL does not change when an incoming request is handled. URL rewriting does change the URL before it sends the request to the webpage.
The Routing is more focused on mapping URL to resources. URL rewriting is focused on mapping a new URL to an older one.
Routing never rewrites our URL. The routing is mapped to the original route of the URL. URL rewriting rewrites our old URL with the new one.
In Routing, if we want to change the URL pattern then we change it in one place, all links that are based on that pattern will automatically use the new pattern. In URL rewriting, if we change any URL pattern then we must change all hyperlinks manually that contain the original URL.
The Routing works with URL and Http method headers The URL rewriting makes a decision based on domain name, HTTP header and server variables.
Routing does not perform any redirection URL rewrite module can perform HTTP redirection.
The ASP.NET routing is fully extensible and customizable. The URL Rewrite module is not extensible in its current version.
ASP.NET Routing can be used only with web applications that are created based on the .Net framework The URL rewrite (IIS) module can use any type of web application like ASP.NET, PHP, Static page Site and so on.

Conclusion

Both URL rewriting and ASP.Net Routing can implement a URL pattern for our web application. In ASP.NET Routing, the request resource resolution logics are within our application means routing related logic is a part of our application, so it is easy to maintain application dependent logic. ASP.NET Routing helps to remove the need for maintain synchronization between our web application and other configurable resources.