Browse Tutorials

02 Intermediate

Understanding Attribute Routing in ASP.NET MVC

Understanding Attribute Routing in ASP.NET MVC

31 Mar 2024
Intermediate
30.8K Views
11 min read

Attribute Routing in ASP.NET MVC: An Overview

In MVC routing is a pattern-matching process that monitors the requests and determines what to do with each request. In other words, we can say Routing is a mechanism for mapping requests within our MVC application.

ASP.NET MVC5 and WEB API 2 support a new type of routing, attribute routing. In this routing, attributes are used to define routes. Attribute routing provides you more control over the URIs by defining routes directly on actions and controllers in your ASP.NET MVC application and WEB API. To know about convention-based routing refer to Routing in Asp.Net MVC with example. In this MVC tutorial, we will understand attribute routing in asp.net mvc5.

Read More: MVC Interview Questions and Answers

Defining Attribute Routing in ASP.NET MVC

1. Controller-level attribute routing

You can define routes at the controller level that apply to all actions within the controller unless a specific route is added to an action.

[RoutePrefix("MyHome")]
[Route("{action=index}")] //default action 
public class HomeController : Controller
{
 //new route: /MyHome/Index 
 public ActionResult Index()
 {
 return View();
 }

 //new route: /MyHome/About 
 public ActionResult About()
 {
 ViewBag.Message = "Your application description page.";
 return View();
 }

 //new route: /MyHome/Contact 
 public ActionResult Contact()
 {
 ViewBag.Message = "Your contact page."; return View();
 }
}

2. Action level attribute routing

You can define routes at the action level that apply to a specific action within the controller.

public class HomeController : Controller
{
 [Route("users/{id:int:min(100)}")] //route: /users/100
 public ActionResult Index(int id)
 {
 //TO DO:
 return View();
 }

 [Route("users/about")] //route" /users/about
 public ActionResult About()
 {
 ViewBag.Message = "Your application description page.";
 return View();
 }

 //route: /Home/Contact
 public ActionResult Contact()
 {
 ViewBag.Message = "Your contact page.";
 return View();
 }
}

Note

  1. Attribute routing should be configured before the convention-based routing.

  2. When you combine attribute routing with convention-based routing, actions that do not have a Route attribute for defining attribute-based routing will work according to convention-based routing. In the above example, Contact action will work according to convention-based routing.

  3. When you have only attribute routing, actions that do not have a Route attribute for defining attribute-based routing will not be part of attribute routing. In this way, they can’t be accessed from outside as a URI.

When to use Attribute Routing?

The convention-based routing is complex to support certain URI patterns that are common in RESTful APIs. But by using attribute routing you can define these URI patterns very easily.

For example, resources often contain child resources like Clients have ordered, movies have actors, books have authors, and so on. It’s natural to create URIs that reflect these relations like as: /clients/1/orders

This type of URI is difficult to create using convention-based routing. Although it can be done, the results don’t scale well if you have many controllers or resource types.

With attribute routing, it’s pretty much easy to define a route for this URI. You simply add an attribute to the controller action as:

[Route("clients/{clientId}/orders")] 
public IEnumerable GetOrdersByClient(int clientId) 
{ 
//TO DO 
}

Why do we need Attribute Routing in ASP.NET MVC Applications?

  • Improved Readability: With attribute routing, you can define routing rules directly within the controller or action method and maintain the routing configuration.
  • Fine-Grained Control: You can specify custom route templates, constraints, and defaults for individual actions, enabling precise mapping of URLs to controller methods.
  • Convention over Configuration: Attribute routing follows the principle of convention over configuration, allowing you to define routing rules closely aligned with the structure of your controllers and actions.
  • Support for Complex Routes: Attribute routing supports complex route configurations, including attribute prefixes, optional parameters, constraints, and route namespaces.
  • Route Centralization: While attribute routing promotes controller-level routing configuration, you can still centralize common route definitions in a separate routing configuration file if needed.

How to use Attribute Routing in ASP.NET MVC?

Enabling Attribute Routing in ASP.NET MVC

Enabling attribute routing in your ASP.NET MVC5 application is simple, just add a call to routes.MapMvcAttributeRoutes() method within RegisterRoutes() method of RouteConfig.cs file.

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

 //enabling attribute routing
 routes.MapMvcAttributeRoutes();
 }
}

You can also combine attribute routing with convention-based routing.

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

 //enabling attribute routing
 routes.MapMvcAttributeRoutes();

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

Defining Attribute Routing for Area in ASP.NET MVC

You can also define attribute routing for a controller that belongs to an area by using the RouteArea attribute. When you define attribute routing for all controllers within an area, you can safely remove the AreaRegistration class for that area.

[RouteArea("Admin")]
[RoutePrefix("menu")]
[Route("{action}")]
public class MenuController : Controller
{
 // route: /admin/menu/login
 public ActionResult Login()
 {
 return View();
 }

 // route: /admin/menu/products
 [Route("products")]
 public ActionResult GetProducts()
 {
 return View();
 }

 // route: /categories
 [Route("~/categories")]
 public ActionResult Categories()
 {
 return View();
 }

 [Route("customers/{customerId}/orders")]
 public IEnumerable GetOrdersByCustomer(int customerId)
 {
 //TO DO
 }
}

Route Constraints

Route constraints let you restrict how the parameters in the route template are matched.


{parameter:constraint}
ConstraintDescriptionExample
alphaMatches uppercase or lowercase Latin alphabet characters (a-z, A-Z){x:alpha}
boolMatches a Boolean value{x:bool}
datetimeMatches a DateTime value.{x:datetime}
decimalMatches a decimal value.{x:decimal}
doubleMatches a 64-bit floating-point value{x:double}
floatMatches a 32-bit floating-point value.{x:float}
guidMatches a GUID value.{x:guid}
intMatches a 32-bit integer value.{x:int}
lengthMatches a string with the specified length or within a specified range of lengths.{x:length(8)} {x:length(2,30)}
longMatches a 64-bit integer value.{x:long}
maxMatches an integer with a maximum value.{x:max(10)}
maxlengthMatches a string with a maximum length.{x:maxlength(10)}
minMatches an integer with a minimum value.{x:min(10)}
minlengthMatches a string with a minimum length.{x:minlength(10)}
rangeMatches an integer within a range of values.{x:range(40,50)}
regexMatches a regular expression.{x:regex(^\d{3}-\d{3}-\d{4}$)}

Can we use both Attribute Routing and Convention-based routing in a single MVC project?

Yes, both the routing mechanisms can be combined in a single ASP.NET MVC project. The controller action methods having the [Route] attribute use Attribute Routing, and the action methods without the [Route] attribute use Convention-based routing.
Summary

I hope you will enjoy the Attribute Routing while working with ASP.NET MVC. I would like to have feedback from my blog readers. Your valuable feedback, questions, or comments about this article are always welcome.

Unlock the Next Level of MVC

FAQs

Q1. What is an example of attribute-based routing?

LendUp implemented TaskRouter to intelligently route customers' calls to different specialists.

Q2. What is the difference between conventional routing and attribute routing in MVC?

The attribute routing allows and requires precise control of which route templates apply to each action

Q3. Which version of ASP.NET MVC offers attribute-based routing?

The MVC 5 supports a new type of routing called “Attribute Routing”. As the name suggests, Attribute Routing enables us to define routing on top of the controller action method.
Share Article
Batches Schedule
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this