×

iFour Logo

What is routing and how to implement attribute routing in Asp.net MVC?

Kapil Panchal - June 29, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
What is routing and how to implement attribute routing in Asp.net MVC?

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.

 

Table of Content

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.

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 ? 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();  
    }  
} 

Defining Route name


We can also set a route name to enable the easy generation of URIs.

Example:

[Route(“Mvctest”,  Name = "myTestURL")]  
public ActionResult Index()  
{  
        ViewBag.Message = "Welcome to ASP.NET MVC!";  
        return View();  
} 

We can generate URIs using the URLs.RouteUrlmethod.

Test URI

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.

What is routing and how to implement attribute routing in Asp.net MVC? 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.   Table of Content 1. Properties of Route 1.1. Route Name 1.2. URL model 1.3. Default 1.4. Constraints 2. Understand the Default Route 3. Enabling Attribute Routing 4. An instance of attribute routing 5. Attribute Routing with optional parameter 6. Route Prefixes 7. Defining Default Route using Route Attribute 8. Defining Route name 9. Conclusion 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 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 ? Your Search ends here. See 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(); } } Defining Route name We can also set a route name to enable the easy generation of URIs. Example: [Route(“Mvctest”, Name = "myTestURL")] public ActionResult Index() { ViewBag.Message = "Welcome to ASP.NET MVC!"; return View(); } We can generate URIs using the URLs.RouteUrlmethod. Test URI 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.

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 

Blog Our insights

React 19 For Business: Latest Features and Updates
React 19 For Business: Latest Features and Updates

When I first started exploring React.js for our company’s project, I felt a bit lost. It was like trying to solve a big puzzle without all the pieces! But as I kept learning and trying them practically, I discovered some really cool features that blew my mind making everything seamlessly easier.

MySQL vs Azure SQL Database: Cost, Security, and Compatibility Considerations
MySQL vs Azure SQL Database: Cost, Security, and Compatibility Considerations

This blog is a continuation of MySQL vs Azure SQL Database – Part 1 , where we compared MySQL and Azure SQL databases. We learned how important it is to identify and evaluate client...

Is It Worth Using Azure With Power Platforms For Financial Business?
Is It Worth Using Azure With Power Platforms For Financial Business?

The era of traditional software development is fading; Azure Cloud and Power Platform services are taking charge to run businesses of the new age. When it comes to Financial business,...