How to use attribute routing in ASP.NET Core
The routing middleware in ASP.Internet Core is adept at mapping incoming requests to the respective route handlers. You can established up routing in ASP.Internet Core in two different ways: attribute-primarily based routing and conference-primarily based routing.
Compared with conference-primarily based routing, in which the routing facts is specified at a single place, attribute routing enables you to apply routing by decorating your action strategies with characteristics. This posting offers a dialogue of how we can get the job done with attribute-primarily based routing in ASP.Internet Core MVC.
To get the job done with the code illustrations presented in this posting, you need to have Visible Studio 2019 set up in your program. If you really do not already have a copy, you can obtain Visible Studio 2019 below.
Generate an ASP.Internet Core 3.one MVC challenge in Visible Studio 2019
First off, let’s create an ASP.Internet Core challenge in Visible Studio 2019. Assuming Visible Studio 2019 is set up in your program, adhere to the actions outlined beneath to create a new ASP.Internet Core challenge in Visible Studio.
- Start the Visible Studio IDE.
- Simply click on “Create new challenge.”
- In the “Create new project” window, choose “ASP.Internet Core World wide web Application” from the listing of templates shown.
- Simply click Next.
- In the “Configure your new project” window, specify the identify and place for the new challenge.
- Optionally verify the “Place remedy and challenge in the very same directory” verify box, depending on your tastes.
- Simply click Generate.
- In the “Create a New ASP.Internet Core World wide web Application” window proven next, choose .Internet Core as the runtime and ASP.Internet Core 3.one (or later on) from the fall-down listing at the prime.
- Pick out “Web Application (Model-Look at-Controller)” as the challenge template to create a new ASP.Internet Core MVC application.
- Be certain that the verify boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be utilizing people capabilities below.
- Be certain that Authentication is established to “No Authentication” as we won’t be utilizing authentication possibly.
- Simply click Generate.
Subsequent these actions will create a new ASP.Internet Core MVC challenge in Visible Studio 2019. We’ll use this challenge in the sections beneath to illustrate how we can get the job done with attribute routing in ASP.Internet Core 3.one.
Generate a controller course in ASP.Internet Core MVC
Generate a new controller named DefaultController and change the default source code of the DefaultController with the subsequent code:
public course DefaultController : Controller
[Route("")]
[Route("Default")]
[Route("Default/Index")]
public ActionResult Index()
return new EmptyResult()
[Route("Default/GetRecordsById/id")]
public ActionResult GetRecordsById(int id)
string str = string.Structure
("The id passed as parameter is: ", id)
return Ok(str)
Use attribute routing at the controller level in ASP.Internet Core
Attribute routing can be used both of those at the controller and action method amounts. If we use the route attribute at the controller level, then the route is applicable to all action strategies of that controller.
If you study our DefaultController course, you are going to notice that the Default route is used several occasions when specifying the route template for the action strategies. The subsequent code snippet reveals how you can specify different route characteristics at the controller level to make a lot more versatile use of attribute routing.
[Route("Default")]
public course DefaultController : Controller
[Route("")]
[Route("Index")]
public ActionResult Index()
return new EmptyResult()
[HttpGet]
Route("Default/GetRecordsById/id")]
public ActionResult GetRecordsById(int id)
string str = string.Structure("The id passed as parameter is: ", id)
return Ok(str)
When utilizing route characteristics both of those at the controller and the action method amounts, the route template utilized at the controller level is prepended to the route template specified at the action method level.
You could possibly typically need to have a typical prefix for your controller. When you do, you need to use the [RoutePrefix] attribute as proven in the code snippet offered beneath.
[RoutePrefix("providers")]
public course HomeController : Controller
//Motion strategies
Use attribute routing at the action method level in ASP.Internet Core
Refer to the DefaultController course proven earlier mentioned. As you can see, we’ve specified a few routes in the Index method of the DefaultController course. This implies that each and every of the subsequent URLs will invoke the Index() action method of the DefaultController.
https://localhost:11277
https://localhost:11277/property
https://localhost:11277/property/index
As in conference-primarily based routing, you can specify parameters in attribute-primarily based routing as nicely. In other words, attribute-primarily based routing enables you to specify route characteristics with parameters. The GetRecordsById action method of the DefaultController course proven earlier is an illustration.
Note that “id” in the specified route represents a parameter or a place holder. The id parameter in this illustration can be anything at all, this sort of as a string or an integer. What if you would like to restrict the parameter to only integers? You can accomplish this by utilizing constraints.
Use attribute route constraints in an action method
Route constraints are used to thwart invalid requests to controller steps. For illustration, you could possibly want to make certain that the parameter passed to an action method is generally an integer. The syntax of utilizing route constraints is parameter:constraint. The subsequent code snippet illustrates this. Note that the id parameter below is generally an integer.
[Route("Default/GetRecordsById/id:int")]
public ActionResult GetRecordsById(int id)
string str = string.Structure("The id passed as parameter is: ", id)
return Ok(str)
Use optional parameters in attribute route specs
You can use optional parameters in your route specification much too. The subsequent code snippet reveals how this can be achieved. Note that the action method in this situation would be executed even if the id parameter is not passed.
[Route("Income/GetSalesByRegionId/id?")]
It’s vital to comprehend that when utilizing attribute routing neither the controller identify nor the action method identify performs any position in deciding upon which action method will be executed. Let us see this with an illustration. The subsequent code snippet illustrates how the URL has been changed in the route specification for the GetRecordsById action method.
[Route("Household/GetRecordsById/id:int")]
public ActionResult GetRecordsById(int id)
string str = string.Structure("The id passed as parameter is: ", id)
return Ok(str)
You can now invoke the GetRecordsById action method utilizing the subsequent URL:
https://localhost:11277/property/GetRecordsById/one
Use several attribute route constraints in an action method
It is also probable to use several constraints to a parameter. The subsequent code snippet illustrates how this can be achieved. Note the minimum amount benefit of the id parameter need to be one, else a 404 mistake will be returned.
[Route("Default/GetRecordsById/id:int:min(one)")]
public ActionResult GetRecordsById(int id)
string str = string.Structure("The id passed as parameter is: ", id)
return Ok(str)
Use HTTP verbs in attribute routes in an action method
You can even use HTTP verbs in attribute routing. The subsequent code snippet reveals how this can be achieved.
[HttpGet]
[Route("Default/GetRecordsById/id:int:min(one)")]
public ActionResult GetRecordsById(int id)
string str = string.Structure("The id passed as parameter is: ", id)
return Ok(str)
Typically used attribute route constraints
Right here is a listing of the most usually used route constraints in ASP.Internet Core.
- bool – used to match a Boolean benefit
- datetime – used to match a DateTime benefit
- decimal – used to match a decimal benefit
- double – used to match a sixty four-little bit floating-issue benefit
- float – used to match a 32-little bit floating-issue benefit
- guid – used to match a GUID benefit
- int – used to match a 32-little bit integer benefit
- extensive – used to match a sixty four-little bit integer benefit
- max – used to match an integer with a optimum benefit
- min – used to match an integer with a minimum amount benefit
- minlength – used to match a string with a minimum amount size
- regex – used to match a normal expression
Generate custom attribute route constraints
You can also create your own custom route constraints by developing a course that extends the IRouteConstraint interface and implements the Match method as proven in the code snippet offered beneath.
public course CustomRouteConstraint : IRouteConstraint
public bool Match(HttpContext httpContext, IRouter route,
string routeKey,
RouteValueDictionary values, RouteDirection routeDirection)
throw new NotImplementedException()
Use token alternative in attribute routes at the controller level
Attribute routing in ASP.Internet Core MVC provides assistance for an additional fascinating characteristic named token alternative. You can use the tokens [action], [area], and [controller] in your controller, and these tokens will be changed by the action, area, and controller names respectively. The subsequent code snippet illustrates how this can be achieved.
[Route("[controller]/[action]")]
public course HomeController : Controller
non-public readonly ILogger_logger
public HomeController(ILoggerlogger)
_logger = logger
public IActionResult Index()
return Look at()
//Other action strategies
Attribute routing in ASP.Internet Core provides you a lot more command and adaptability around the URIs in your internet application. Though conference-primarily based routing can be configured at a single place, which can in convert be utilized to all controllers in your application, it is tough to assistance specified URI patterns (this sort of as API versioning) with conference-primarily based routing.
By utilizing attribute routing, you can decouple the controller and action names from the route template. You can even use a mix of conference-primarily based routing and attribute-primarily based routing in your ASP.Internet Core applications.
How to do a lot more in ASP.Internet Core:
Copyright © 2020 IDG Communications, Inc.