Routing in ASP.NET MVC

As discussed in the previous post, an ASP.Net MVC  application is a complete shift from traditional ASP.Net application.

A traditional ASP.Net application is a collection of webpages (generally aspx files) hosted on a server which can be requested by a client, while an ASP.Net MVC application is a system , which acts as  a service. It can be considered as a collection of methods\ activities that are executed on client request. The result of this execution is returned back to the client.

An ASP.Net application lifecycle mainly involves following activities :

  1. Routing incoming requests  –  performed by routing engine and router.
  2. Performing actions corresponding to the request  – performed by Controllers and Controller actions.
  3. Returning back the result to the client  -performed by  Views or ActionResults.
Let us first start with Routing.
URL ROUTING
URL routing is a critical component in ASP.Net MVC application. This is because URL routing is the one that determines how an incoming client (browser) request gets mapped onto a MVC controller and controller action i.e. in other words which controller will handle which request.
URL Routing uses something called as route table. A route table is nothing but a collection of routes. And what is a route?
Well, a route is a complete definition for how to dispatch a web request to a controller. So, basically a route holds an information of which request should be handled by which controller.
The following diagram shows a brief overview of how routing happens.
URL Routing module 
The URL routing is generally carried out by a URL routing module. The URL routing module is othing but an HTTPModule class in ASP.Net MVC. Hence a URL routing module is generally an instance of HTTPModule class.
The first thing to do in an ASP.Net MVC application is to register the URL Routing module i.e to assign an HTTPModule class as the URL Routing Module. This is generally done in the web.config file, present in the project solution. In the file, there is an element called as httpModules.
Making an entry in this httpModules element marks the registeration of URL Routing Module.  Generally, we do not have to register the routing module , as it part of the template which is created by the Visual Studio IDE during the creation of the project.
As discussed before, the Url Routing Module is implemented by creating an HTTPModule instance. The HTTPModule  interscepts all the request coming into your MVC web application.

Always be careful not to delete this module section from the web.config file as everything would stop working.

Route Table 
The URL routing module takes advantage of something called as a “route table” and the route table is used to do the mapping between the incoming request and MVC Controller action.

The route table is generally setup and manipulated in the global.asax file.  The global.asax file generally handles the application life cycle events such as Application start, Application end.

The route table is setup in the Application Start event through a function called as RegisterRouter.  The RegisterRoute  sets up the route table which contains just one route entry.

We create the route in the route table by calling the MapRoute method. In this case, the MapRoute method is creating a “default route” which is used by the MVC application. This “default route” is used to handle around 85% of incoming requests.

There are different types of System defined routes, “default” route is one of them. You can also create your own routes too. We will have a look at this later in the blog.

Getting back to MapRoute, MapRoute is used to make a route entry in the route table. It takes three parameters, viz. ,

  • Route name: There are some unique ways to identify different routes in the routes table. “default” route is one of them, which is used to identify a default route i.e if no matching route is obtained for an incoming request then the default route is called.
  • Url : This parameter does two things :
    1. It sets the pattern of the request that this route is going to intercept i.e what kind (pattern)  of incoming request will this route act on.
    Eg: In case of the entry MapRoute (“Default”, {controller}/{action}/{id}, new {controller=”Home”, action=”Index”, id=””}), it says that the “Default” route will handle a request which will have the pattern {some xxx}/{some xxx}/ {some xxx} – such as http://localhost:8080/Samples/Entry/9.2. The other thing that this url parameter does is map different segments in the Url to different parameter names.
    Eg: In case of the entry MapRoute (“Default”, {controller}/{action}/{id}, new {controller=”Home”, action=”Index”, id=””}), The first value should be stored in a parameter (or variable) called as controller,  the second value should be stored in a parameter (or variable) called as action and third value should be stored in parameter(or variable)  called as id. So in http://localhost:8080/Samples/Entry/9 – Samples will be stored in a parameter (or variable) called as controller, Entry will be stored in a parameter (or variable) called as action and 9 will be stored in a parameter (or variable) called as id.In short : MapRoute (“Default”, {controller}/{action}/{id}, new {controller=”Home”, action=”Index”, id=””}) ,says,
    The URL will be in the form {firstvalue}/{secondvalue}/{thirdvalue} where first value will be called controller, second value will be called action and third value will be  called id.
  • Defaults Value : This 3rd parameter sets the default values to each of the parameters established \ created in the 2nd parameter. So in case if either of the parameter does not have any value then the take on these default values.  Eg:  In case of the entry MapRoute (“Default”, {controller}/{action}/{id}, new {controller=”Home”, action=”Index”, id=””}),  controller, action and id are the parameter names or variables created in second parameter. So if the incoming request has no value for controller then the controller will have value “Home” ,  Similarly if  request has no corresponding value for action then the action will have value “Index” and Similarly if no corresponding value is found for id then id will be ” ” (empty).
So, in case if the browser makes a request http://localhost:8080/ then the request is executed as if http://localhost:8080/Home/Index/ was called, because the default values are “Home” for first value, “Index” for second, hence as no value were specified the incoming request was converted to http://localhost:8080/Home/Index/.
If the above concept is understood, then lets try intercepting one more route.
MapRoute(“ArchiveRoute”, Archive/{entrydata}, new {controller=”Archive”,  action=”Entry”})
This route is made to handle any request which starts with Archive. Eg: http://localhost:8080/Archive/….
The secondvalue  i.e the one after Archive will be represented by entryData (0r will be stored in a variable called entryData).
The default values for controller will be “Archive” and for action will be “Entry”.
controller and action are predefined parameters while entryData is userdefined parameter which can be accessed as a parameter in the ArchiveController’s  entry function (or action).

We will make this new entry using MapRoute method in the RegisterRoutes function. Now the routes table works on the basis of  First Match Algorithm i.e the first matching route is executed. Hence if default route is kept as the first entry in the table then all the incoming request will be intercepted using the default route or in other words will be mapped to this route. This is because the default route is the one which has to be executed if no matching routes are found. Hence always add “default” route at the end so that it gets executed if no relevant route is found.
 
(To be continued…)
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