Krishan Dutt Sharma

Web Developer

Routing In MVC 5

What is Routing : 

Routing is a mechanism to process the incoming URL that is more descriptive and gives desired response. In this case, URL is not mapped to specific files or folder as was the case of earlier days websites.

There are two types of routing

Convention based routing – to define this type of routing, we call MapRoute method and set its unique name, URL pattern and specify some default values.
Attribute-based routing – to define this type of routing, we specify the Route attribute in the action method of the controller.

Route:  Route Define the Url Pattern and handler information. All the configured route store into the route table and use the routing engine to determine the appropriate handler class for the incoming request.

Configure Route:

Every MVC application must configure (register) at least one route, which is configured by 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.

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

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

As you can see in the above figure, the route is configured using the MapRoute() extension method of RouteCollection, where the name is “Default”, URL pattern is “{controller}/{action}/{id}” and defaults parameter for the 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.

The same way, you can configure other routes using the MapRoute method of RouteCollection. This RouteCollection is actually a property of RouteTable class.

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

Define the new Route in MVC :

to define the new route in MVC, go to ~/app_start/RouteConfig.cs and write new route just after the routes.IgnoreRoute Statement.

Routeconfig.cs File Code:

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

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

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

Notice the above code, we have defined MyNewRoute just after routes.IgnoreRoutes and the default route “Default”. This is because the default route defined is more of a generic nature that takes care of any three segments passed in the URL for Controller, Action, and Id (optional). So if we define our custom route after the default routes, the default routes will execute and our custom routes will never execute. So while defining new routes, we need to define from specific to generic routes.

In our custom route, we have instructed ASP.NET MVC framework that if any URL request is starting with MyEmployees, route it through MyCustomRoute routes rules.

Route Constraints:

You can also apply restrictions on the value of the 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.

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 RouteConfig class, you need to register it in the Application_Start() event in the Global.asax. So that it includes all your routes into RouteTable.

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

Catchall in ASP.NET MVC route :

Sometimes, we need to write a route for catchall type of URL where we can catch any extra data coming in with the URL after URL segments defined in the route. To do this, we can write in following way.

routes.MapRoute("CatchAll", "Route/{controller}/{action}/{id}/{*catchall}",
          new { controller = "RoutingStuffs", action = "CatchAll", id =
          UrlParameter.Optional });

Notice the last segment of the URL pattern ({*catchall}) In above case, any URL starting with “Route” is served by this route. For example

http://localhost:63087/Route/RoutingStuffs//CatchAll/50

Above URL is served by this route where Controller is “RoutingStuffs”, the action is “CatchAll” (name of the action method) and ID is 50 given to the action method.

However, in case the URL comes like

http://localhost:63087/Route/RoutingStuffs/CatchAll/50/Delete/And/Other/Parameter

The remaining data after “/50/”, the id segment is given to the controller action method as catchall parameter notice the “{*catchall}” segments defined in the URL pattern.

public ActionResult CatchAll(string id = null, string catchall = null)
        {
            ViewBag.Action = "Priority: CatchAll";
            ViewBag.Controller = "Priority: RoutingStuffs";
            ViewBag.Id = id;
            ViewBag.CatchAll = catchall;

            return View("/Views/RoutingStuffs/OtherStuffs/CatchAll.cshtml");
        }

Notice the 2nd parameter of the above action method. “catchall”, the name of this parameter should match with the last segment defined in the route {*catchall}. The value of “catchall” parameter would be “/Delete/And/Other/Parameter” in this case.