;

Routing in ASP.NET MVC


Tutorialsrack 18/02/2021 C# ASP.NET MVC

In this article, we will learn about routing in ASP.NET web applications. Routing plays a vital role in the ASP.NET MVC web applications.

In this article, we will discuss 

  • What is Routing in ASP.NET MVC?
  • Why use routing?
  • How does it work?
  • Properties of Route
  • Basic Understanding of the Routing
  • Types of Routing
  • Custom Routing

By the end of this article, you have a basic understanding of Routing in ASP.NET MVC. 

What is ASP.NET Routing?

The ASP.NET Routing is a pattern matching mechanism that is responsible for mapping the incoming request from the browser to specific controller actions. 

Why use routing?

In the ASP.NET WebForm application, each URL must match with a particular “.aspx file. For example, a URL “http://www.example.com/empinfo.aspx must match with the file “empinfo.aspx which contains the code and markup for rendering a response to the browser.

To Overcome the problem of mapping each URL to the physical file. ASP.NET introduces the Routing. In ASP.NET WebForm request handler is “.aspx” file and in ASP.NET MVC request handler is a controller and an action method.

For Example, “http://www.example.com/employees” can be mapped to “http://www.example.com/empinfo.aspx” in ASP.NET Webforms and the same URL can be mapped to Employee Controller and Index action method in MVC.

How does it work?

  • When the web application is running then the application registers one or more patterns with the framework's route table to tell the routing engine what to do with any requests that match those patterns. 
  • When the route engine receives a request at runtime, it matches the requested URL pattern against the pattern URL registered with the route table and returns the response according to the pattern match. 
  • If the Incoming URL pattern found in the RouteTable returns the desired response and if the incoming URL pattern is not found in the RouteTable then it returns the HTTP 404 error which means URL Not Found.

Properties of Routes

A URL contains the Following properties as follows:

  • Route Name: A route name may be used as a specific reference to a given route. And it Must Be unique. By defaults, RouteName is the default.
     
  • URL Pattern: A URL pattern can contain literal values and variable placeholders (referred to as URL parameters). The literals and placeholders are located in segments of the URL that are delimited by the slash (/) character.

    When a request is made, the URL is parsed into segments and placeholders, and the variable values are provided to the request handler. This process is similar to the way the data in query strings is parsed and passed to the request handler. In both cases, variable information is included in the URL and passed to the handler in the form of key-value pairs. For query strings, both the keys and the values are in the URL. For routes, the keys are the placeholder names defined in the URL pattern, and only the values are in the URL.
     
  • Defaults: When you define a route, you can assign a default value for a parameter. The default is an object that contains default route values.
     
  • Constraints: A set of constraints to apply against the URL pattern to more narrowly define the URL that it matches. In other words, You use route constraints to restrict the browser requests that match a particular route. You can use a regular expression to specify a route constraint.

Basic Understanding of the Default Route

The ASP.NET MVC framework comes out with a default route. The default routing template also displays the property names of the route attributes, so it is easier for a beginner to understand what’s going on. You can find the Default Routes in the App_Start folder in RouteConfig.cs file. Let’s have a look at the default route:

Example - Default Route
public static void RegisterRoutes(RouteCollection routes) {
  // Ignore the Url thats end with .axd Extension
  routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

  routes.MapRoute(
  name: "Default", // Route Name. Each Route has a Unique Name

  url: "{controller}/{action}/{id}", // URL Pattern to be Mapped

  // Default Values for the URL
  defaults: new {
    controller = "Home",
    action = "Index",
    id = UrlParameter.Optional
  });
}

Note: 

  • Each route has a unique name. The default name of the route is Default.
  • URL attributes describe the pattern of the URL. And the default pattern of the URL is “controller/action/id”.
  • The defaults Attributes sets default properties for the controller, action, and sets the id as optional. The default values are used when no values for the attribute are passed.

The valid URLs for this route are as follows:

  • /
  • /Home
  • /Admin
  • /Home/Index
  • /Home/Index/123abc
  • /Home/Index/abc

Additionally to the default route, the ASP.NET MVC template implements the routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);.

This is used for ignoring the Url that ends with .axd Extension or you can define other extensions to ignore routes.

Types of Routing

There are two types of routing in ASP.NET as follows:

  1. Convention Based Routing
  2. Attribute-Based Routing

Convention Based Routing: To define the Convention Based Routing, we call the MapRoute method and set its unique name, URL pattern, and specify some default values.

Example of Convention based Routing

Example - Convention based Routing
routes.MapRoute(
                name: "Default",    // Route Name, Each Route has a Unique Name

                url: "{controller}/{action}/{id}", // URL Pattern to be Mapped

                // Default Values for the URL
                defaults: new { controller = "Home", action = "Index",
                                id = UrlParameter.Optional }
            );

Attribute-Based Routing: The Attribute Routing introduced in ASP.NET MVC 5. To define the Attribute-Based Routing, we specify the Route attribute above the action method of the controller or above the controller. To use attribute-based routing, you need to enable it first in RouteConfig.cs file.

Example for Enable Attribute-Based Routing

Example - Enable Attribute-Based Routing
public static void RegisterRoutes(RouteCollection routes)
{
       // Ignore the Url thats end with .axd Extension
       routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

       routes.MapMvcAttributeRoutes();      
}

Example of Attribute-based Routing

Example - Attribute based Routing
[Route("home")]
public ActionResult Index() {
	return View();
}

Custom Routing in ASP.NET MVC

For most of the requests, your web application's default route will work fine, however, you might have different needs to which are not satisfied by the default routing of ASP.NET MVC. So you can create a custom route for your web applications.

For example, sometimes you need to URL structure like this as given below:

  • “{language}-{country}/{controller}/{action}”
  • “{date}/{controller}/{action}”
  • “blog/{articletitle}” 

So you can create your own custom routing for your controller action methods.

Note: when you create a custom route for your web application, keep one thing in mind that the custom routing is always placed above the Default Route in case of Convention Based Routing. 

Example of Custom Routing

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

    //Custom Route
    routes.MapRoute(
    name: "CustomRoute", url: "blog/{articletitle}", defaults: new {
      Controller = "Home",
      action = "articleDetails"
    });

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

I hope this article will help you to understand the basic concepts of routing in ASP.NET MVC.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags