Routing in. NetCore MVC (1) routing configuration basis, coremvc

Source: Internet
Author: User

Routing in. NetCore MVC (1) routing configuration basis, coremvc
Routing in. NetCore MVC (1) routing configuration Basics

 

0x00 routing plays a role in MVC

Some time ago, I was busy with other things and finally finished learning. NetCore. The topic of this study is routing in MVC. Routing is a component implemented by all MVC frameworks. The core function is to follow the Path in the received Http Request (for http: // localhost/Home/Index/12? For test = 555, http is the protocol, localhost is the domain, Home/Index/12 is the Path, and test = 555 is the parameter), and matches with the rules in the routing rule set in sequence, after successful match, the corresponding Action in the corresponding Controller processes the Http request. If no match is found, Error 404 is returned.

 

Most MVC Framework routing rules are configured similarly. Generally, routing rules are configured using templates. Some also support more fine-grained configuration through Attribute (annotation in Java) on Controller and Action.

. NetCore MVC supports configuring routing rules through a global routing template, and fine-grained routing configuration through Attribute on the Controller and Action. The following describes how to configure global routing rules in Startup. cs.

0x01 configure routes in Startup. cs

The so-called routing template is a string. When an Http request is received, the Path is taken out and compared with the template, if a template is matched, It is routed to the corresponding Controller and Action for processing. In the Configure method in the Startup. cs file, we can Configure the routing when adding the MVC function. For example:

app.UseMvc(routes =>{    routes.MapRoute(        name: "default",        template: "{controller}/{action}/{id}");});

The name is the name of the routing rule, and the template is the routing template. This also introduces our first concept, the variables in the routing template.

1. variables in the routing Template

In the template "{controller}/{action}/{id}", variables in the routing template are enclosed in curly brackets. For example, a variable does not have to match a fixed string in the Path, but plays a placeholder role, for example, the template above can match the Path in three parts separated by "/". For example, a/B/c can be matched successfully. The values of each variable are extracted from the corresponding part of the Path. For example

Home/Index/12 can be matched, where controller is Home, action is Index, and id is 12

The Home/Index match fails because there are only two parts.

Home/Index/12/34 also fails because it exceeds three parts.

After the template matches successfully, the route is extracted based on the controller and action:

Home/Index/12 is routed to the Index method of HomeController. The variable id is 12.

Test/Show/AB routes the Show method to TestController. The variable id is AB.

2. variable value acquisition

In the Index or Show method, we can extract variables in two ways:

One is to add parameters with the same name as the variables in the parameter list of the method. MVC will automatically find and convert the parameters from the Variable list to the corresponding type:

public IActionResult Index(string id, string controller, string action){    ViewData["Message"] = "id is " + id + ",  controller is " + controller + ",  action is " + action;    return View();}

The other is to retrieve from RouteData:

public IActionResult Index(){    var controller = RouteData.Values["controller"].ToString();    var action = RouteData.Values["action"].ToString();    var id = RouteData.Values["id"].ToString();    ViewData["Message"] = "id is " + id + ",  controller is " + controller + ",  action is " + action;    return View();}

The variable names in the routing template can be customized, but the controller and action (including the area mentioned later) are special variables. The value extracted by the controller is the name of the Controller, and the value extracted by the action is the name of the method in the Controller. To allow each routing rule to be routed to the Controller and Action, the controller and action variables should appear in the routing template. However, you can also specify the default values for the controller and action variables, this will be replaced by the default value if this parameter is omitted in Path.

3. Default Value of the Variable

You can configure the default values of variables in two ways:

app.UseMvc(routes =>{    routes.MapRoute(        name: "default",        template: "{controller=Home}/{action=Index}/{id=0}");});

Or

routes.MapRoute(    name: "default",    template: "{controller}/{action}/{id}",    defaults: new     {        controller = ”Home”,        action = ”Index”,        id = 0,    });

In this way, the part with default values in the Path can be omitted. The omitted rules are the same as those with default values in C #. For example:

The null Path will be routed to HomeController, Index Method

Test will be routed to TestController, Index Method

Test/Show will still be routed to TestController, Show Method

Generally, I will use the first method to configure the default value, which is more intuitive and convenient. But sometimes some requirements are hard to achieve in the first method. For example, if I want to configure the route to TestShow for the Show method of TestController, use the first method to configure it as follows: "TestShow/{controller = Test}/{action = Show }", in this way, when Path is TestShow, it can be routed to the Show method of TestController, but when Path is TestShow/Home/Index, it will be routed to the Index method of HomeController.

Configure using the second method:

routes.MapRoute(    name: "test",    template: "TestShow",    defaults: new     {        controller = ”Test”,        action = ”Show”,     });

When Path is TestShow, the Show method of TestController can be routed. However, if Path is Test/Home/Index, the template cannot be matched. A better way to configure fine-grained routing is to configure the Test method using the Route Attribute, which will be discussed later.

4. Static characters in routing rules

In addition to using variables to configure routing templates, you can also use static strings. Static strings can be used independently or in combination with variables.

For example, the template is:

"Durow/{controller}/{action }"

Durow/Home/About will be routed to HomeController, About Method

Durow/Test/Show routes to TestController, Show Method

You can also mix static characters and variables. For example, the configuration template is:

"My {controller}/My {action }"

MyHome/MyAbout will be routed to HomeController, About Method

MyTest/MyShow will be routed to TestController, Show Method

5. Use? Variable marker (optional)

In addition to providing default values for variables, can you also use? Mark variables as optional. For example, template

"{Controller}/{action}/{id ?}"

The id is an optional variable.

Both Home/Index and Home/Index/12 match successfully.

6. Use * to extract all the remaining parts of the Path

If a template needs to match the Path containing any part (Segments), you can use the * symbol to specify the variable, using the * variable, all the remaining parts of the Path are extracted after matching is completed. For example, the template:

"{Controller}/{action}/{id ?} /{* Others }"

Home/Index/12/a/B/c/d, it will route to the Index method of HomeController, id is 12, others is a/B/c/d

In fact, from the perspective of template matching, the template above can match all paths. The only problem is that the corresponding Controller and Action may not exist after matching.

7. Select multiple routing rules

In practice, multiple routing rules may be configured. When a Path is received, more than one rule can be matched.

The simplest is to configure the following two templates:

"{Controller}/{action = About }"

"{Controller}/{action = Index }"

When Path is Home, both routes can match. How can we choose one? In fact, it is very simple and crude, that is, to see which route is in front. That is to say, once the Path matches the template successfully, the routing will be implemented immediately and the subsequent template will be ignored. For the above configuration, Home will be routed to the About method of HomeController. Therefore, you must pay attention to the sequence When configuring the route.

0x02 use Attribute to configure a route

In addition to configuring global routing rules in Startup. cs, you can also configure routes for a single Controller and its actions. The method is to use the Route feature on the Controller class and Action method. For example, use the Route feature on the Show method of TestController:

[Route("TestShow")]public IActionResult Show(){    return View();}

When Path is TestShow, You can route the Show method to TestController.

As we mentioned above when introducing the default value, we use global template Configuration:

routes.MapRoute(    name: "test",    template: "TestShow",    defaults: new     {        controller = ”Test”,        action = ”Show”,     });

You can also achieve the same purpose. However, when using the latter method, if there are templates such as "{controller}/{action}", in addition to TestShow, if Path is Test/Show, you can match this template and route it to the Show method of TestController. After the Route feature is configured on the Show method, only TestShow can be routed. Even if a template such as "{controller}/{action}" exists at the same time, Test/Show cannot be routed.

The first time I used the Route feature to configure routes, I was confused about how the routing component routed the Path to the corresponding Controller and Action. Then I went to a breakpoint and looked at the RouteData object, it is found that for the Action method configured with a route, its controller is the name of the Controller where the method is located, and action is the name of the method, in addition, the {controller} variable and {action} variable cannot be used in the routing template configured by the Route feature. This ensures that the Path matching the template can always be routed to this Action.

The Route feature configured on the Controller class is finally configured on each Action in the Controller. For example, if we configure Route ("TestShow") on TestController, we actually Configure Route ("TestShow") for each method. Therefore, when Path is TestShow, an error is returned, two matching actions are prompted. Then, how should I configure routes for the Controller through Route? [controller] and [action] can be used.

[Controller] and [action] In the Route feature

For [controller] and [action], I do not know how to call it. It cannot be called a variable. The function is similar to a placeholder. When we use the Route feature in the Controller class to configure routes, if [controller] and [action] are used, when the Route feature configures routes for each Action in the Controller, [controller] is replaced with the Controller name, and [action] is replaced with the Action name. For example, configure the Route feature for TestController as Route ("durow/[controller]/[action]"). For the Index method, the routing template is durow/Test/Index, the controller is Test, and the action is Index. For the Show method, the routing template is durow/Test/Show, the controller is Test, and the action is Show. As mentioned above, MVC creates an ActionDescriptor object for each Action to store the route information of this Action. For actions configured with the Route feature (repeat it, configuring the Route feature for the Controller class is equivalent to configuring the Route feature for each Action in the Controller), there will be an AttributeRouteInfo object in the ActionDescriptor, this object is blank for actions without configuring the Route feature. AttributeRouteInfo contains the routing template information.

 

Therefore, the configuration of the Route feature of TestController above can be set to Route ("durow/Test/[action]") to achieve the same effect. However, the Route ("durow/[controller]/[action]") semantics is stronger and more common.

Use variables in the Route feature

Variables can also be used to configure a template in the Route feature? Optional. For example, you can configure Route for TestController ("durow/[controller]/[action]/{id ?}"). However, note that the default values (including [controller] and [action]) cannot be used for variables in the template of the Route feature, and * cannot be used to extract all the remaining parts of the Path.

0x03 written at the end

I have written so much about it. In fact, it is very likely that no complicated routing is used in actual use. Generally, a general rule and an Area-related rule are enough. But with a detailed understanding of routing rules, you can have a more open mind when you encounter some special needs in the future. The following describes the constraints and custom constraints in the routing template. We will discuss how to use Areas later.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.