Posted on 3/26/2020 11:31:32 PM by Admin

Routing in Asp.Net MVC

If you have gone through my previous article ,then you should have a little bit of idea about Asp.Net MVC request response mechanism.

In Asp.Net MVC we do not directly request for a physical page like we used to do in Asp.Net Webform, instead the URL is consisted of a Controller and an Action Name ,the controller's Action Method handles the request and processes it. And finally we get the desired response whether it be a HTML,a JSON or XML .

Now ,wait and think, how the request is actually being served, how the url is being mapped with appropriate Controller and Action, Who is doing that?

Don't you think there is a third person who is extracting the Controller name and Action name from the URL and then mapping it to appropriate Controller and Action Method for processing.

That third person is Routing Module also called as HttpRoutingModule.

Now ,you can say a route is a URL pattern and the mechanism which monitors the incoming request and determines which controller and which action will handle the request for further processing is Routing.

As the request is finally processed by any Controller and it's Action Method ,They are called as Handler.

Actually, In MVC life Cycle routing is the first state.

Routing in MVC
Routing in MVC

Now the question arises ,how actually routing module works?

The routing engine uses the route table for matching the incoming URL.Route table can be considered as the collection of different routes.

we can register as many routes (URL pattern) as we want, but at least one is necessary.

Now you will be curious to know how to register route and where actually the route table resides?

How to define routing in MVC:-

In Global.asax file In application_start event RegisterRoute method of RouteConfig class is called,which is a static method.

So as application starts all the routes defined in RegisterRoute method gets registered in RouteTable.


  protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }

Now,Go to AppStart------>RouteConfig.cs------->RegisterRoute().

In short RouteConfig is the class which is responsible for registering routes.In RouteConfig class RegisterRoute method is defined which has parameter of type RouteCollection.

This RouteCollection is nothing but a get only static property of RouteTable class where you want your URL pattern to be registered.

The RouteCollection has an extension method, mapRoute which expects three parameters:-
  1. Name:-The name of your URl Pattern which must be unique.
  2. URL:-the URL pattern.
  3. Defaults:-Default values for your Controller and Action.

By specifying the above parameters you can register your routes.Let us understand it with some examples.


    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 }
            );
        }

In a MVC application, a route table must have at least one route definition.In the above example ,the route template named "Default" is added to the route table.The URL pattern contains the controller and action placeholder.The default values tells the routing engine to invoke default value if any of the placeholder is empty meaning when corresponding value is not supplied.

IgnoreRoute method defined above takes care of the files that are not for routing and should be ignored like files with extension axd will be auto ignored and no one can fetch such file from URL.

URL matching depends on the below condition:-
  • The default value that is added in the route table.
  • The order in which the route is added.
  • The constraint that are provided for the route.
  • Routing pattern that defines route.

As the order of routes matters so it is recommended to put the more generic routes at the bottom.For example the default route should always come after custom routes.

Lets create one Action in controller and define custom route for that.


   public ContentResult GetArticle(string atricleName,string TopicName,string subtopicName)
        {
            return Content("Article :-"+atricleName+"Topic:-"+TopicName+"subtopic:-"+subtopicName);
        }

Here the GetArticle method is expecting 3 parameters,if we want these parameters to be passed in the url as routed data then we will have to define a route for the same like below.


   routes.MapRoute(
   name: "Article",
   url: "article/{atricleName}/{TopicName}/{subtopicName}",
               defaults: new {Controller="Article",Action="GetArticle" atricleName = "", TopicName = "", subtopicName = "" }
           );

In the above route definition I have not used any placeholder for Controller and Action, so in the URL we do not need to specify any controller or action name ,the default value will take care of that. Any URL that will start with article will be mapped with article controller and GetArticle action, we just need to provide the rest of the three parameters or it will be null by default.