The routing middleware in ASP.Net Core is adept at mapping incoming requests to the respective route handlers. You can established up routing in ASP.Net Core in two different approaches: attribute-centered routing and conference-centered routing.
Not like conference-centered routing, in which the routing facts is specified at a one spot, attribute routing enables you to employ routing by decorating your motion solutions with characteristics. This article presents a discussion of how we can function with attribute-centered routing in ASP.Net Core MVC.
To function with the code examples presented in this article, you need to have Visual Studio 2019 set up in your method. If you don’t presently have a copy, you can down load Visual Studio 2019 here.
Create an ASP.Net Core three.one MVC venture in Visual Studio 2019
1st off, let’s make an ASP.Net Core venture in Visual Studio 2019. Assuming Visual Studio 2019 is set up in your method, adhere to the techniques outlined beneath to make a new ASP.Net Core venture in Visual Studio.
- Start the Visual Studio IDE.
- Click on “Create new venture.”
- In the “Create new project” window, select “ASP.Net Core World wide web Application” from the checklist of templates exhibited.
- Click Up coming.
- In the “Configure your new project” window, specify the name and spot for the new venture.
- Optionally check out the “Place answer and venture in the identical directory” check out box, depending on your choices.
- Click Create.
- In the “Create a New ASP.Net Core World wide web Application” window proven future, select .Net Core as the runtime and ASP.Net Core three.one (or later on) from the drop-down checklist at the leading.
- Find “Web Software (Design-Look at-Controller)” as the venture template to make a new ASP.Net Core MVC software.
- Make sure that the check out packing containers “Enable Docker Support” and “Configure for HTTPS” are unchecked as we will not be employing those people options here.
- Make sure that Authentication is established to “No Authentication” as we will not be employing authentication possibly.
- Click Create.
Following these techniques will make a new ASP.Net Core MVC venture in Visual Studio 2019. We’ll use this venture in the sections beneath to illustrate how we can function with attribute routing in ASP.Net Core three.one.
Create a controller class in ASP.Net Core MVC
Create a new controller named DefaultController and replace the default source code of the DefaultController with the pursuing code:
public class 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 handed as parameter is: ", id)
return Alright(str)
Use attribute routing at the controller stage in ASP.Net Core
Attribute routing can be utilized both equally at the controller and motion system amounts. If we implement the route attribute at the controller stage, then the route is applicable to all motion solutions of that controller.
If you analyze our DefaultController class, you will observe that the Default route is utilized multiple occasions when specifying the route template for the motion solutions. The pursuing code snippet displays how you can specify different route characteristics at the controller stage to make extra adaptable use of attribute routing.
[Route("Default")]
public class 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 handed as parameter is: ", id)
return Alright(str)
When employing route characteristics both equally at the controller and the motion system amounts, the route template applied at the controller stage is prepended to the route template specified at the motion system stage.
You may usually need to have a prevalent prefix for your controller. When you do, you need to use the [RoutePrefix] attribute as proven in the code snippet supplied beneath.
[RoutePrefix("solutions")]
public class HomeController : Controller
//Action solutions
Use attribute routing at the motion system stage in ASP.Net Core
Refer to the DefaultController class proven previously mentioned. As you can see, we have specified 3 routes in the Index system of the DefaultController class. This indicates that each of the pursuing URLs will invoke the Index() motion system of the DefaultController.
http://localhost:11277
http://localhost:11277/household
http://localhost:11277/household/index
As in conference-centered routing, you can specify parameters in attribute-centered routing as very well. In other terms, attribute-centered routing permits you to specify route characteristics with parameters. The GetRecordsById motion system of the DefaultController class proven before is an case in point.
Be aware that “id” in the specified route represents a parameter or a position holder. The id parameter in this case in point can be just about anything, this kind of as a string or an integer. What if you would like to restrict the parameter to only integers? You can attain this by employing constraints.
Use attribute route constraints in an motion system
Route constraints are utilized to thwart invalid requests to controller steps. For case in point, you may want to be certain that the parameter handed to an motion system is always an integer. The syntax of employing route constraints is parameter:constraint. The pursuing code snippet illustrates this. Be aware that the id parameter here is always an integer.
[Route("Default/GetRecordsById/id:int")]
public ActionResult GetRecordsById(int id)
string str = string.Structure("The id handed as parameter is: ", id)
return Alright(str)
Use optional parameters in attribute route technical specs
You can use optional parameters in your route specification way too. The pursuing code snippet displays how this can be achieved. Be aware that the motion system in this scenario would be executed even if the id parameter is not handed.
[Route("Revenue/GetSalesByRegionId/id?")]
It’s significant to understand that when employing attribute routing neither the controller name nor the motion system name plays any part in picking out which motion system will be executed. Let’s see this with an case in point. The pursuing code snippet illustrates how the URL has been adjusted in the route specification for the GetRecordsById motion system.
[Route("Household/GetRecordsById/id:int")]
public ActionResult GetRecordsById(int id)
string str = string.Structure("The id handed as parameter is: ", id)
return Alright(str)
You can now invoke the GetRecordsById motion system employing the pursuing URL:
http://localhost:11277/household/GetRecordsById/one
Use multiple attribute route constraints in an motion system
It is also attainable to implement multiple constraints to a parameter. The pursuing code snippet illustrates how this can be achieved. Be aware the least price of the id parameter need to be one, else a 404 error will be returned.
[Route("Default/GetRecordsById/id:int:min(one)")]
public ActionResult GetRecordsById(int id)
string str = string.Structure("The id handed as parameter is: ", id)
return Alright(str)
Use HTTP verbs in attribute routes in an motion system
You can even use HTTP verbs in attribute routing. The pursuing code snippet displays how this can be achieved.
[HttpGet]
[Route("Default/GetRecordsById/id:int:min(one)")]
public ActionResult GetRecordsById(int id)
string str = string.Structure("The id handed as parameter is: ", id)
return Alright(str)
Commonly utilized attribute route constraints
In this article is a checklist of the most normally utilized route constraints in ASP.Net Core.
- bool – utilized to match a Boolean price
- datetime – utilized to match a DateTime price
- decimal – utilized to match a decimal price
- double – utilized to match a 64-bit floating-stage price
- float – utilized to match a 32-bit floating-stage price
- guid – utilized to match a GUID price
- int – utilized to match a 32-bit integer price
- prolonged – utilized to match a 64-bit integer price
- max – utilized to match an integer with a most price
- min – utilized to match an integer with a least price
- minlength – utilized to match a string with a least duration
- regex – utilized to match a typical expression
Create custom made attribute route constraints
You can also make your possess custom made route constraints by generating a class that extends the IRouteConstraint interface and implements the Match system as proven in the code snippet supplied beneath.
public class CustomRouteConstraint : IRouteConstraint
public bool Match(HttpContext httpContext, IRouter route,
string routeKey,
RouteValueDictionary values, RouteDirection routeDirection)
toss new NotImplementedException()
Use token replacement in attribute routes at the controller stage
Attribute routing in ASP.Net Core MVC supplies assistance for a further interesting feature named token replacement. You can use the tokens [motion], [location], and [controller] in your controller, and these tokens will be replaced by the motion, location, and controller names respectively. The pursuing code snippet illustrates how this can be achieved.
[Route("[controller]/[motion]")]
public class HomeController : Controller
personal readonly ILogger_logger
public HomeController(ILoggerlogger)
_logger = logger
public IActionResult Index()
return Look at()
//Other motion solutions
Attribute routing in ASP.Net Core gives you extra handle and flexibility more than the URIs in your web software. Though conference-centered routing can be configured at a one spot, which can in convert be applied to all controllers in your software, it is difficult to assistance specified URI designs (this kind of as API versioning) with conference-centered routing.
By employing attribute routing, you can decouple the controller and motion names from the route template. You can even use a combination of conference-centered routing and attribute-centered routing in your ASP.Net Core purposes.
How to do extra in ASP.Net Core:
Copyright © 2020 IDG Communications, Inc.