Understanding the Routing framework

Asp.Net MVC Routing framework is the core of every Asp.Net MVC request. This means whenever an end user hits for a particular url, the routing framework came in to play.

Routing framework is basically a pattern matching system. The Routing System uses a series of rules listed in a routing table [App_Start\RouteConfig.cs] to determine which Controller and Action are executed in response to a request intercepted by the routing engine. When a URL is found to match a pattern, the routing engine attempts to match the text in the placeholders. If it cannot find a match, it returns a 404 HTTP Status Code. This whole concept is shown in the following image :

https://learnwithshahriar.wordpress.com/

Please note, Each routing rule contains placeholders that can match a controller, an action, and any number of variables. Variable data can be passed to the request handler without requiring a query string.

Now, Lets have a look on RouteConfig.cs file which is located under “App_Start” folder.  Routing engine basically matches the pattern of the received url against the RouteCollection registered in the following file.

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

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }

As you can see, the default code snipped that ships with the MVC template does not only used for providing a Name and URL  pattern but also defines a set of default parameter. In case,  the routing engine does not find a perfect match it starts filling values that are not provided by the URL from the default values.

If you want to map new routes you simply add your desired routes in this file(RouteConfig.cs). You add the route to the application by adding the Route object to the static Routes property of the RouteTable class. The Routes property is a RouteCollection object that stores all the routes for the application.

Note:

When adding new routes ALWAYS KEEP IN MIND that you have to add specific route on the top and followed by more generic route in the end. Otherwise your web app will never receive proper routing.

In the next post I will discuss about “Attribute Routing” . Till then have fun !

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s