w3resource

Routing in ASP.NET MVC


In the previous tutorial, we learnt about the folder structure of the ASP.NET application and about the different configuration files. In this tutorial we will explore routing system of ASP.NET MVC application.

Routing per se is not specific to any language or framework. It is used in almost all MVC frameworks, though it might be implemented differently.

Routing eliminates the need of mapping every URL to a particular physical file, rather it enables us to define a URL pattern which maps to a request handler, which can either be a method, a class or a file.

Routes

Routes are defined URL patterns which helps the routing engine to direct an incoming request accordingly. Configured routes in an application are stored in the routing table.

The figure below pictorially illustrates the routing actions of routes in an MVC application.

asp.net routes

Configure a Route

In a ASP.NET application, route patterns are configured in the App_Start/RouterConfig.cs file inside the RouteConfig class. By default, ASP.NET routes are configured using the pattern "{controller}/{action}/{id}" with the defaults as HomeController and Index action.

asp.net configure a route

URL Pattern

URL patterns are the remaining part of the URL after the domain name. By default, ASP MVC has this URL pattern "{controller}/{action}/{id}" which can be explained as localhost:8080/{controller}/{action}/{id}. Anything after "localhost:8080/" would be considered as controller name. The same way, anything after controller name would be considered as action name and then a parameter, which could be optional.

When the controller and the action is not specified like in http://localhost:8080, the default controller and action handles the request and by default the default controller is the HomeController and action is index.

Multiple Routes

ASP.NET offers us the flexibility of creating multiple routes patterns using it MapRoute function. This function accepts two compulsory parameters and optional one. The route name and url pattern is compulsory while the parameter is optional.

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

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute(
            name: "Activity",
            url: "activities/{id}",
            defaults: new {controller = "Activity", 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, URL pattern for the Activity route is activities/{id}, which specifies that any URL that starts with domainName/activities, must be handled by ActivityController. Notice that we haven't specified {action} in the URL pattern because we want every URL that starts with student should always use Index action of StudentController. We have specified default controller and action to handle any URL request which starts from domainname/activities.

It should be noted that routes are evaluated from the top to bottom, like in the above, the activity routes must be evaluated before the default routes.

Route Constraints

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

Example:

routes.MapRoute(
        name: "Activity",
        url: "student/{id}/{name}/{activituid}",
defaults: new { controller = "Activity", action = "Index", id = UrlParameter.Optional, name = UrlParameter.Optional, activity = UrlParameter.Optional },
        constraints: new { id = @"\d+" }
    );

When a non-numeric value for id parameter for is given, that request will be handled by another route else if there are no other matching routes "The resource could not be found" error will be thrown.

Register Routes

When we have configured all the routes in RouteConfig class, we need to register it in the Application_Start() event in the Global.asax. so that, they can be added in the application route table

Route registration sample:

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

We have thus far seen the importance of route in an MVC application, in the upcoming tutorials, we will explore other functionalities in the ASP.NET platform.



Inviting useful, relevant, well-written and unique guest posts