Routing in ASP.NET MVC

Routing in ASP.NET MVC Application

In this article, I am going to discuss Routing in ASP.NET MVC Application with some examples. Routing is one of the most important features of ASP.NET MVC Framework. As part of this article, we are going to discuss the following pointers.

  1. What is Routing?
  2. What are the different types of Routing supported by ASP.NET MVC?
  3. How does the Routing in ASP.NET Web Form?
  4. What is a Route in ASP.NET MVC Application?
  5. How Does the Routing work in ASP.NET MVC Application?
  6. How to Configure a Route in ASP.NET MVC?
  7. Understanding the URL Pattern in ASP.NET MVC Routing
  8. How to Register Routes in ASP.NET MVC?
  9. Examples to understand Routing.
What is Routing in ASP.NET MVC?

The ASP.NET Routing module is responsible for mapping the incoming browser requests (i.e. the incoming URL) to a particular MVC controller action method. This mapping is done by the routing rules defined for your application. For example, if we issue a request to the “/Home/Index” URL, then it is the Index action method of Home Controller class which is going to handle the request as shown in the below image.

How Routing work in asp.net mvc?

Routing is not new or specific to ASP.NET MVC framework. It can also be used with our traditional ASP.NET WebForms application.

What are the different types of Routing supported by ASP.NET MVC?

In ASP.NET MVC application, we can define routes in two ways. They are as follows:

  1. Convention Based Routing
  2. Attribute-Based Routing.

In this article, I am going to discuss the Convention Based Routing in ASP.NET MVC Application.

How does the Routing in ASP.NET Web Form?

As we know in ASP.NET Web Forms application, each and every URL should be matched with a specific .aspx file. For example, a URL http://dotnettutorials/employeeinfo.aspx must match with a physical file i.e. employeeinfo.aspx that contains necessary code and HTML for rendering the response to the browser. So in case of ASP.NET Web Forms, the URL pointing to the file must have its physical existence.

Then ASP.NET Framework introduced the concept of Routing to eliminate the needs of mapping each and every URL to a physical file. The Routing enables us to define the URL pattern that maps to the request handler. This request handler can be a class or file.

In case of ASP.NET Webform application, the request handler is a file (i.e. aspx file) and in case of ASP.NET MVC Framework, the request handler is the Controller Actions. For example, http://dotnettutorials/employees can be mapped to http://dotnettutorials/employeeinfo.aspx in ASP.NET Webforms application and the same URL can be mapped to Employee Controller and Index action method in ASP.NET MVC application.

What is a Route in ASP.NET MVC Application?

A Route is a URL pattern that is mapped to a handler. The handler can be a physical file, such as an aspx file in case of WebForms application. A handler can also be a class that processes the request, such as a controller in case of an MVC application. That means the Route defines the URL pattern and the handler information. All the configured routes of an ASP.NET MVC application stored in the RouteTable and this Route table will be used by the Routing engine to determine the appropriate handler class or file for an incoming request.

How Does the Routing work in ASP.NET MVC Application?

The following diagram illustrates the Routing process.

Routing in ASP.NET MVC Application

In simple word, we can say that ASP.NET MVC Routing is a pattern matching mechanism that handles the incoming request (i.e. incoming URL) and figures out what to do with that incoming request (i.e. incoming URL).

At runtime, Routing engine uses the Route table for matching the incoming request’s URL pattern against the URL patterns defined in the Route table. We can register one or more URL patterns to the Route table at Application_Start event.

When the routing engine finds a match in the routing table for the incoming request, it forwards the request to the appropriate controller and action. If there is no match found in the routing table for the incoming request, then it simply returns a 404 HTTP status code.

The routing functionality is implemented in the System.Web.Routing.

How to Configure a Route in ASP.NET MVC?

Every MVC application must configure (register) at least one route in the RouteConfig class and by default MVC Framework provide one default route. But you can configure as many as routes you want. You can register a route in the RouteConfig class, which is in RouteConfig.cs file under the App_Start folder as shown below.

The following code illustrates how to configure a Route in the RouteConfig class.

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

            routes.MapRoute(
                name: "Default", //Route Name
                url: "{controller}/{action}/{id}", //Route Pattern
                defaults: new
                {
                    controller = "Home", //Controller Name
                    action = "Index", //Action method Name
                    id = UrlParameter.Optional //Defaut value for above defined parameter
                }
            );
        }
    }
}
Let’s Understand the above Code:

As you can see in the above code, the Routing is configured using the MapRoute() extension method of RouteCollection class, where the Route name is “Default” and the URL pattern is “{controller}/{action}/{id}“. The Defaults value for the controller is Home, and the default action method is Index and the id parameter is optional.

Here Defaults specifies which controller, action method or value of id parameter should be used if they do not exist in the incoming request URL. In the same way, you can configure other routes using the MapRoute method of RouteCollection. That we will discuss in our next article.

Note: Always remember route name should be unique across the entire application. Route name can’t be duplicated.

Understanding the URL Pattern in ASP.NET MVC Routing:

The URL pattern is considered only after the domain name in the URL. For example, Suppose your web application is running on www.dotnettutorials.net then the URL pattern “{controller}/{action}/{id}”  for your application would be look like www.dotnettutorials.net/{controller}/{action}/{id}.

Anything after the “www.dotnettutorials.net/” would be considered as the controller name. The same way, anything after the controller name would be considered as the action name and the value of the id parameter.

Hence you need to provide the controller name followed by action name and id if it is required. If you will not provide any of the value then default values of these parameters will be provided by the routing system that means the default controller and action method will handle the request.

How to Register Routes in ASP.NET MVC?

After configuring the routes in RouteConfig class, you need to register it in the Application_Start() event in the Global.asax file. So that it includes all your routes into the RouteTable.

Global.asax

namespace FirstMVCDemo
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }
}

To understand ASP.NET MVC Routing lets create a controller called HomeController as shown below

namespace FirstMVCDemo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
}
Example to understand Routing:
  1. http://localhost:53605/ => controller = Home, action = Index, id = none, since default value of controller and action are Home and Index respectively.
  2. http://localhost:53605/Home => controller = Home, action = Index, id = none, since default value of action is Index
  3. http://localhost:53605/Home/Index => controller = Home, action = Index, id=none
  4. http://localhost:53605/Home/Index/5 => controller = Home, action = Index, id = 5

The default route that ASP.NET MVC Framework creates for you when you create a new project assumes that you will follow this convention approach. But if you want to follow your own convention then you would need to modify the routes or you need to create your own routes.

In the next article, I a, going to discuss how to create Custom Routes in ASP.NET MVC application. Here, in this article, I try to explain the Routing in ASP.NET MVC. application step by step with a simple example. I hope you enjoy this article.

Leave a Reply

Your email address will not be published. Required fields are marked *