Routing in MVC

ASP DOT NET MVC ROUTING

In this article, I will talk about one of the most important features of ASP.NET MVC application called ASP DOT NET MVC Routing. 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.

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

By the end of this article, you will understand how the standard route table maps the requests (i.e. incoming URL) to specific controller actions. But before understanding the routing in MVC let’s first understand how Routing is implemented in our traditional ASP.NET Web Forms application.

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 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.

Route:

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 Web Forms 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.

The following diagram illustrates the Routing process

ASP DOT NET MVC Routing .

Let’s Understand the Architecture:

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 route table for the incoming request, it forwards the request to the appropriate controller and action. If there is no match found in the route table for the incoming request, then it simply returns a 404 HTTP status code.

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

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 ASP DOT NET MVC Routing is configured using the MapRoute() extension method of RouteCollection class, where

The Route name is “Default”

The URL pattern is “{controller}/{action}/{id}

The Defaults value for the controller is Home, action method is Index and 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.

The same way, you can configure other routes using 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.

The URL Pattern:

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 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.

Register Routes

After configuring the routes in RouteConfig class, you need to register it in the Application_Start() event in the Global.asax. 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 DOT NET MVC Routing lets create a controller called as HomeController as shown below

namespace FirstMVCDemo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
}
Request URL:

http://localhost:53605/ => controller = Home, action = Index, id = none, since default value of controller and action are Home and Index respectively.

http://localhost:53605/Home => controller = Home, action = Index, id = none, since default value of action is Index

http://localhost:53605/Home/Index => controller = Home, action = Index, id=none

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 will discuss how to create Custom Routes in ASP.NET MVC application.

If you want to learn more then please visit the MSDN site.

SUMMARY

In this article, I try to explain the ASP DOT NET MVC Routing. application step by step with a simple example. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

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