[Translation] ASP. NET Core 2.0 routing engine details, asp. netcore
This article introduces the detailed explanation of ASP. NET Core 2.0 routing engine and shares it with you as follows:
Problem
How does the routing engine of ASP. NET Core 2.0 work?
Answer
Create an empty project and add the MVC service and request middleware to the Startup class:
public void ConfigureServices(IServiceCollection services){ services.AddMvc();} public void Configure(IApplicationBuilder app, IHostingEnvironment env){ app.UseMvc(routes => { routes.MapRoute( name: "goto_one", template: "one", defaults: new { controller = "Home", action = "PageOne" }); routes.MapRoute( name: "goto_two", template: "two/{id?}", defaults: new { controller = "Home", action = "PageTwo" }); routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); });}
Create a controller HomeController to demonstrate the General Routing:
public class HomeController : Controller{ public IActionResult Index() { return Content("Home/Index"); } public IActionResult PageOne() { return Content("Home/One"); } [HttpGet] public IActionResult PageTwo() { return Content("(GET) Home/Two"); } [HttpPost] public IActionResult PageTwo(int id) { return Content($"(POST) Home/Two: {id}"); }}
Create a controller WorkController to demonstrate the feature routing:
[Route("work")]public class WorkController : Controller{ public IActionResult Index() { return Content("Work/Index"); } [Route("one")] public IActionResult PageOne() { return Content("Work/One"); } [HttpGet("two")] public IActionResult PageTwo() { return Content("(GET) Work/Two"); } [HttpPost("two/{id?}")] public IActionResult PageTwo(int id) { return Content($"(POST) Work/Two: {id}"); }}
Discussion
The routing engine of ASP. NET Core can map incoming requests to controllers and their methods. This is achieved by adding routing middleware to the request pipeline. Specifically, IRouteBuilder is used to map URL rules (templates) to a controller.
Routing Template
The routing template can use the nominal value and label (identify the routing parameters ). When a route is matched, the literal value strictly matches the text in the URL, and the tag is replaced.
To match a template, the template must contain the controller and method tag to locate the Controller method (this is the core information of MVC ). Other parameters in the template marked as method parameters (implemented by model binding ).
When adding a route ing, you can provide the default value for the tag. It is useful when the template does not contain controllers and methods. The template can also contain optional tags corresponding to method parameters.
Let's look at a sample template:
contact/{controller=Home}/{action=Index}/{id?}
Note the following:
1. The tag contains braces. There are three tags: controller, action, and id.
2. The template contains a contact value, which matches the text in the URL.
3. default values have been provided for controller (Home) and action (Index.
4. Optional tags are declared by question marks.
The following URL matches the template:
- /Contact/Home/Index/1: All tags have values.
- /Contact/Home/Index: the Optional flag is ignored.
- /Contact/Home: if the action flag is ignored, the default Index is used.
- /Contact: the controller and action tags are ignored. The default values Home and Index are used respectively.
Regular route
A general route creates a convention for the URL path. For example, a template is given:
1. The first tag is mapped to the Controller.
2. The second tag is mapped to the method.
3. The third tag maps to an optional method parameter id.
You can also omit controllers and methods from the template, as long as you provide them with default values. For example, the following route maps to the address/one, because defaults provides the required controller and method labels:
routes.MapRoute( name: "goto_one", template: "one", defaults: new { controller = "Home", action = "PageOne" });
Note: before adding a route entry to a common route entry, the route entry is executed in the defined order. Once a route entry matches successfully, the entire matching process ends.
Because routing middleware only uses controllers and method tags to map to a controller method, multiple methods with the same name in the same controller will throw an exception. To solve this problem, you can use the IActionConstraint features on the method (such as HttpGet and HttpPost ):
[HttpGet("two")]public IActionResult PageTwo(){ return Content("(GET) Work/Two");} [HttpPost("two/{id?}")]public IActionResult PageTwo(int id){ return Content($"(POST) Work/Two: {id}");}
===== Start by sanshi ===============================
To observe exceptions in methods with the same name in the controller, we first need to modify the Configure () method to add the exception handling middleware during development:
public void Configure(IApplicationBuilder app, IHostingEnvironment env){ if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(routes => ....);}
Modify HomeController:
public IActionResult PageTwo(){ return Content("(GET) Home/Two");}public IActionResult PageTwo(int id){ return Content($"(POST) Home/Two: {id}");}
A seemingly normal overload function, but an exception is thrown when it is put in the controller.
In the browser address bar, enter http: // localhost: 65415/Home/PageTwo to view the exception page:
===== End by sanshi =============================
Feature Routing
Feature routing is implemented by directly providing routing templates for controllers and methods.
You can use the [Route] or [HttpGet] (or other verb) feature to specify the template. These templates can contain nominal values and tags (not controller and method tags ).
During runtime, the Controller's feature templates and method's feature templates are merged. For example, in WorkController, The PageOne method can be accessed through/work/one:
[Route("work")]public class WorkController : Controller{ [Route("one")] public IActionResult PageOne() { return Content("Work/One"); }}
Source code download
Original article: https://tahirnaushad.com/2017/08/20/asp-net-core-mvc-routing/
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.