What is routing and how to implement attribute routing in Asp.net MVC?
Tags: aspnet, dotnet, webdev, programming
Published: 2023-08-21 05:12:22

ASP.NET MVC routing is a model mapping system that is responsible for mapping incoming browser queries with specified MVC controller actions. When the ASP.NET MVC application is launched, the application records one or more of the models with the frame route table to specify the routing engine what to do with any request which corresponds to these models. When the routing engine receives a query at runtime, it matches the URL of that query with the URL templates saved with it and gives the response based on a model match.

## Properties of Route
ASP.NET MVC routes are responsible for determining what controller method should be run for a specific URL. An URL is comprised of the following properties:

### Route Name:
A route is a URL model which is mapped to an administrator. A handler may be a controller in the MVC app that handles the request. The name of a route may be used as a specific reference for a particular route.

### URL model:
A URL model can contain literal values and variable substitutes (called URL parameters). When a query is made, the URL is parsed into segments and placeholders, and variable values are given to the query manager. This process is similar to how data in query chains are analyzed and passed to the query manager. In either case, the information about the variables is included in the URL and passed to the handler key-value pairs. For query strings, buttons and values can be found in the URL. For routes, keys are the names of reserved spaces defined in the URL template, and only values are in the URL.

### Default:
When you set a path, you can assign a default value to a parameter. The default value is an object that holds the default path values.

### Constraints:
A set of constraints to be applied against the URL model to define the corresponding URL more narrowly.

## Understand the Default Route

The default ASP.NET MVC project templates add a generic route that uses the following URL convention to split the URL of a particular query into three named segments.

```
url: "{controller}/{action}/{id}"

```

This trace is recorded via the RouteCollection MapRoute() extension method.

Routing is how ASP.NET MVC associates a URI with an action. MVC 5 supports a new type of routing, known as attribute-based routing. As its name indicates, attribute routing uses attributes to specify routes. Attribute Routing provides you with more control over the URIs of your web application.

Routing is a filtering process that oversees requests and determines what to do with each request. Thus, we can say that Routing is a query mapping mechanism in our MVC application.

When an MVC application first boots up, the global.asax Application_Start() event is called. Routing is a screening process that monitors applications and determines what to do with each application.

Example:

```
routes.MapRoute(  
  "Default",
  "{controller}/{action}/{id}",
  new { controller = "Home", action = "Index", ID =  (Url Parameter. Optional)} 
); 

```

MVC 5 supports a new routing type known as “Attribute Routing”. As the name implies, Attribute Routing allows us to define routing above the controller's method of action.

Read More: [Best Way To Bind Partial View For Improving Performance In Asp.net Mvc](https://www.ifourtechnolab.com/blog/best-way-to-bind-partial-view-for-improving-performance-in-asp-net-mvc)

## Enabling Attribute Routing
To enable attribute routing, we must call the MapMvcAttributeRoutes method in the route collection class during setup.

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

```

We may also add a personalized itinerary in the same method. This allows us to combine Attribute Routing with Convention-based routing.

```
public class RouteConfig  
{  
  public static void RegisterRoutes(RouteCollection routes)  
  {  
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
    routes.MapMvcAttributeRoutes();   
    routes.MapRoute(  
      "Default", 
      "{controller}/{action}/{id}", 
      new { controller = "Home", action = "Index", ID =  (Url Parameter. Optional)}  
    );  
  }  
} 

```

## An instance of attribute routing
A path attribute is set at the top of an action method. The following is an example of a Route attribute where routing is set when the action method is set.

In the following instance, I set the route attribute above the action method.

```
public class HomeController: Controller  
{  
  [Route(“Mvctest”)]  
  public ActionResult Index()  
  ViewBag.Message = "Welcome to ASP.NET MVC!";  
    return View();  
}} 

```

## Attribute Routing with optional parameter

We can also set an optional parameter in the URL template by setting a query point ('?") for the route parameter. We can also specify the default value using parameter=value.

```
public class HomeController: Controller  
{  
    [Route(“Mvctest /{ customerName ?}”)]  
    public ActionResult OtherTest(string customerName)  
        ViewBag.Message = "Welcome to ASP.NET MVC!";  
        return View();  
    }  
   [Route(“Mvctest /{ customerName =0036952}”)]  
   public ActionResult OtherTest(string customerName)  
    {  
        ViewBag.Message = "Welcome to ASP.NET MVC!";  
        return View();  
    }  
} 

```

## Route Prefixes

We can also set a common prefix for the entire controller (all controller action methods) with the "RoutePrefix" attribute.

Example:

```
[RoutePrefix(“Mvctest”)]  
public class HomeController : Controller  
{  
    [Route]  
    public ActionResult Index()  
    {  
        ViewBag.Message = "Welcome to ASP.NET MVC!";  
        return View();  
    } 
    [Route(“{ customerName }”)]  
    public ActionResult OtherTest(string customerName)  
    {  
        ViewBag.Message = "Welcome to ASP.NET MVC!";  
        return View();  
    }  
} 

```

Using a tide sign (~) with the Route attribute will replace the route prefix.

### Looking to [hire dedicated ASP.Net developer](https://www.ifourtechnolab.com/hire-asp-net-developer)? Your Search ends here.

Example:

```
[RoutePrefix(“Mvctest”)]  
public class HomeController: Controller  
{  
    [Route(“~/NewMVCTest”)]  
    public ActionResult Index()  
    {  
        ViewBag.Message = "Welcome to ASP.NET MVC!";  
        return View();  
    }  
} 

```

## Defining Default Route using Route Attribute
We can also set an attribute Route above the controller, to capture the default action method as a parameter.

Example:

```
[RoutePrefix(“Mvctest”)]  
[Route(“action=index”)]  
public class HomeController : Controller  
{  
    public ActionResult Index()  
    {  
        ViewBag.Message = "Welcome to ASP.NET MVC!";  
        return View();  
    }   
    public ActionResult NewMethod()  
    {  
        ViewBag.Message = "Welcome to ASP.NET MVC!";  
        return View();  
    }  
} 

```

We can generate URIs using the URLs.RouteUrlmethod.

```
<a href="@Url.RouteUrl(" mainmenu="">Test URI</a>

```

## Conclusion
In this blog, we have learned about what is Routing and implementation of Attribute routing. Attribute Routing provides us with more control over the URIs of our MVC web application. Previous routing mode (convention-based routing) is fully supported by this version of MVC. We may also use the two types of routing within the same project.