Today, I am going to demonstrate what is routing in Asp.Net MVC and how do we use it in our Asp.Net MVC application. Routing is used to map the incoming request to particular MVC controller action. So, Routing is a pattern matching system that map incoming request with specific action. Route table is used to decide at run time to match the incoming request by Route Engine.

When you create a new project in Asp.Net MVC then it creates a default route for the application. You can add multiple route patterns inside the route table as per your requirement.

Basically, you can add routes in a method that is called from the “Application_Start” event in the Global.asax file. 

Following are code snippet from Global.asax with default route.

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

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

It is register in Global.asax file on Application_Start.

protected void Application_Start()
{
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
}

 

 
Example of Routing 

 

Example 1: http://mydomain.com

Here I am not providing any controller or action name. So, it will go with default Url where controller=”Home” and action=”Index”.

 

Note: when we don’t define any controller and action than it goes with default route.

 

Example 2: http://mydomain.com/blog

Here I am giving the controller name only in url after my domain name. So, it will search for default action Index” inside the blog controller.

 

Example 3: http://mydomain.com/blog/mypost

Here I have defined controller name as well as action. So, It will search action=”mypost” inside the controller=”blog”.

 

Example 4: http://mydomain.com/blog/mypost/10

Here it will go with that route which takes a parameter with controller="blog" and action ="mypost"

 

Example 5: http://mydomain.com/blog/mypost/toppost/20

Here using only simple routing you cannot achieve this. It can be achieve by using custom routing.

Refer my last post about Custom Routing.
 

Conclusion:

So, Today we learned what is routing in Asp.Net MVC and also see different example to handle route.

I hope this post will help you. Please put your feedback using comment which helps me to improve myself for next post. If you have any doubts please ask your doubts or query in the comment section and If you like this post, please share it with your friends. Thanks