Tutorialsteacher

Follow Us

Routing in MVC

In the ASP.NET Web Forms application, every URL must match with a specific .aspx file. For example, a URL http://domain/studentsinfo.aspx must match with the file studentsinfo.aspx that contains code and markup for rendering a response to the browser.

Routing is not specific to the MVC framework. It can be used with ASP.NET Webform application or MVC application.

ASP.NET introduced Routing to eliminate the needs of mapping each URL with a physical file. Routing enables us to define a URL pattern that maps to the request handler. This request handler can be a file or class. In ASP.NET Webform application, request handler is .aspx file, and in MVC, it is the Controller class and Action method. For example, http://domain/students can be mapped to http://domain/studentsinfo.aspx in ASP.NET Webforms, and the same URL can be mapped to Student Controller and Index action method in MVC.

Route

Route defines the URL pattern and handler information. All the configured routes of an application stored in RouteTable and will be used by the Routing engine to determine appropriate handler class or file for an incoming request.

The following figure illustrates the Routing process.

Routing in MVC

Configure a Route

Every MVC application must configure (register) at least one route configured by the MVC framework by default. You can register a route in RouteConfig class, which is in RouteConfig.cs under App_Start folder. The following figure illustrates how to configure a route in the RouteConfig class .

Configure Routes in MVC

As you can see in the above figure, the route is configured using the MapRoute() extension method of RouteCollection, where name is "Default", url pattern is "{controller}/{action}/{id}" and defaults parameter for controller, action method and id parameter. Defaults specify 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 the RouteCollection class. This RouteCollection is actually a property of the RouteTable class.

URL Pattern

The URL pattern is considered only after the domain name part in the URL. For example, the URL pattern "{controller}/{action}/{id}" would look like localhost:1234/{controller}/{action}/{id}. Anything after "localhost:1234/" would be considered as a controller name. The same way, anything after the controller name would be considered as action name and then the value of id parameter.

Routing in MVC

If the URL doesn't contain anything after the domain name, then the default controller and action method will handle the request. For example, http://localhost:1234 would be handled by the HomeController and the Index() method as configured in the default parameter.

The following table shows which Controller, Action method, and Id parameter would handle different URLs considering the above default route.

URLControllerActionId
http://localhost/homeHomeControllerIndexnull
http://localhost/home/index/123HomeControllerIndex123
http://localhost/home/aboutHomeControllerAboutnull
http://localhost/home/contactHomeControllerContactnull
http://localhost/studentStudentControllerIndexnull
http://localhost/student/edit/123StudentControllerEdit123

Multiple Routes

You can also configure a custom route using the MapRoute extension method. You need to provide at least two parameters in MapRoute, route name, and URL pattern. The Defaults parameter is optional.

You can register multiple custom routes with different names. Consider the following example where we register "Student" route.

Example: Custom Routes
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Student",
            url: "students/{id}",
            defaults: new { controller = "Student", action = "Index"}
        );

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

As shown in the above code, the URL pattern for the Student route is "students/{id}", which specifies that any URL that starts with domainName/students, must be handled by the StudentController. Notice that we haven't specified "{action}" in the URL pattern because we want every URL that starts with students should always use the Index() action of the StudentController class. We have specified the default controller and action to handle any URL request, which starts from domainname/students.

MVC framework evaluates each route in sequence. It starts with the first configured route, and if incoming URL doesn't satisfy the URL pattern of the route, then it will evaluate the second route and so on. In the above example, routing engine will evaluate the Student route first and if incoming URL doesn't start with /students then only it will consider the second route which is the default route.

The following table shows how different URLs will be mapped to the Student route:

URLControllerActionId
http://localhost/student/123StudentControllerIndex123
http://localhost/student/index/123StudentControllerIndex123
http://localhost/student?Id=123StudentControllerIndex123

Route Constraints

You can also apply restrictions on the value of the parameter by configuring route constraints. For example, the following route applies a limitation on the id parameter that the id's value must be numeric.

Example: Route Constraints
routes.MapRoute(
        name: "Student",
        url: "student/{id}/{name}/{standardId}",
        defaults: new { controller = "Student", action = "Index", id = UrlParameter.Optional, name = UrlParameter.Optional, standardId = UrlParameter.Optional },
        constraints: new { id = @"d+" }
    );

So if you give non-numeric value for id parameter, then that request will be handled by another route or, if there are no matching routes, then "The resource could not be found" error will be thrown.

Register Routes

Now, after configuring all the routes in the 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.

Example: Route Registration
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }
}

The following figure illustrate Route registration process.

Register Route

Thus, routing plays important role in MVC framework.