[Asp.net core series] 4. Higher and stronger routing

0. Preface

Before, we introduced the request to find the controller through routing, and the data flow between the controller and the view. So, let's go back and look at some other uses of routing.

image

1. Route Attribute

According to the direct translation in English, Routing Attribute means routing attributes, but in fact, Attribute is the official name of Microsoft. Well, so I personally think that Route Attribute should be characteristic routing, routing characteristics.

Well, let's put aside the problem of naming for the time being, friends know that this is a routing configuration scheme marked with Attribute. The routing settings we have learned before are all set through the routing table, and Route Attribute is another solution.

1.1 How to set

This kind of scheme is mainly set through the RouteAttribute class. Let's take a look at what this class looks like:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class RouteAttribute : Attribute, IRouteTemplateProvider
{
   public RouteAttribute(string template);
   public string Name { get; set; }
   public int Order { get; set; }
   public string Template { get; }
}

AttributeUsage This feature is used to mark the scope of application of the feature, which AttributeTargets.Class | AttributeTargets.Method means that this feature can be set on a class or method. AllMultiple indicates whether multiple settings are allowed, and Inherited indicates whether the subclasses of the class marked with this feature automatically inherit this feature.

So, we understand the scope of application of RouteAttribute, continue to look at this class, there are a total of three attributes:

  • Name represents the name of this routing feature

  • Order represents the order of activation, the smaller the value, the earlier it will be matched. By default it is 0

  • Template routing analysis template, that is, the format string of the routing table introduced in "[asp.net core series] 2 Controllers and Routing Enmity"

So much has been introduced, let’s try it out first, take out the MvcWeb project created in the previous article, and create a new controller:

using Microsoft.AspNetCore.Mvc;

namespace MvcWeb.Controllers
{
   public class RouteTestController: Controller
   {
       public IActionResult Index()
       {
           return View();
       }
   }
}

Create the corresponding view:

Views > RouteTest > Index.cshtml

Write something casually in Index.cshtml, and then save it.

Then, add a Route attribute tag to RouteTestController:

[Route("/Route")]
public IActionResult Index()
{
   return View();
}

Start the project, http://localhost:5006/Route after the visit  , if nothing happens, you can see an interface similar to the following figure:

那么我们试一试通过路由表设置的路径是否可以访问:

http://localhost:5006/RouteTest

可以看到提示404,也就是说这个Action无法通过路由表的形式查找到了。

1.2 设置参数

我们知道所谓的Action其实也是一个方法,而我们通常请求一个网址的时候,网址中也带有一些查询参数。所以,这一节我们就介绍一下路由特性(属性路由)如何设置参数的解析吧。

1.2.1 不做任何操作

在RouteTestController里添加方法:

[Route("/route/norest")]
public IActionResult NoRest(string name)
{
   ViewBag.Name = name;
   return View();
}

创建对应的View:

<h1>@ViewBag.Name</h1>

启动程序,并访问:http://localhost:5006/route/norest

添加 ?name=test 在上一个请求的后面:

image

尝试变更name的值,可以发现网页中的值也发生了变化,证明我们可以获取到这个值。

1.2.2 当做请求目录的一部分

在上一小节中,没有对参数做任何操作,以查询参数的形式传递。在这一篇,我们可以把参数设置为请求的一部分,像目录那样,修改上一节示例代码为:

[Route("/route/norest/{name}/")]
public IActionResult NoRest(string name)
{
   ViewBag.Name = name;
   return View();
}

请求方式:

http://localhost:5006/route/norest/1232

image

修改连接中的1232 内容,然后刷新页面,就能发现页面中的值也发生了变化

1.2.3 给参数一个默认值

之前的设置里我们都默认参数由请求URL获取,那么在这里我们介绍一下给参数一个值:

[Route("/route/norest/{name=demo}/")]
public IActionResult NoRest(string name)
{
   ViewBag.Name = name;
   return View();
}

访问连接:

http://localhost:5006/route/norest/

可以看见:

image

设置为可空,也就是参数可以不传:

[Route("/route/norest/{name?}/")]
public IActionResult NoRest(string name)
{
   ViewBag.Name = name;
   return View();
}

访问连接:

http://localhost:5006/route/norest/

可以看到页面没有任何显示:

image

正常情况下,如果不对参数设置可空而且参数被我们当做目录的一部分时,不给值是会提示404。

1.3 路由约束

约束 示例 匹配项示例 说明
int {id:int} 123456789,-123456789 匹配任何整数
bool {active:bool} trueFALSE 匹配 true 或false。不区分大小写
datetime {dob:datetime} 2016-12-312016-12-31 7:32pm 在固定区域性中匹配有效的 DateTime 值。请参阅前面的警告。
decimal {price:decimal} 49.99-1,000.01 在固定区域性中匹配有效的 decimal 值。请参阅前面的警告。
double {weight:double} 1.234-1,001.01e8 在固定区域性中匹配有效的 double 值。请参阅前面的警告。
float {weight:float} 1.234-1,001.01e8 在固定区域性中匹配有效的 float 值。请参阅前面的警告。
guid {id:guid} CD2C1638-1638-72D5-1638-DEADBEEF1638 匹配有效的 Guid 值
long {ticks:long} 123456789,-123456789 匹配有效的 long 值
minlength(value) {username:minlength(4)} Rick 字符串必须至少为 4 个字符
maxlength(value) {filename:maxlength(8)} MyFile 字符串不得超过 8 个字符
length(length) {filename:length(12)} somefile.txt 字符串必须正好为 12 个字符
length(min,max) {filename:length(8,16)} somefile.txt 字符串必须至少为 8 个字符,且不得超过 16 个字符
min(value) {age:min(18)} 19 整数值必须至少为 18
max(value) {age:max(120)} 91 整数值不得超过 120
range(min,max) {age:range(18,120)} 91 整数值必须至少为 18,且不得超过 120
alpha {name:alpha} Rick 字符串必须由一个或多个字母字符(a-z,不区分大小写)组成。
regex(expression) {ssn:regex(^\\d{{3}}-\\d{{2}}-\\d{{4}}$)} 123-45-6789 The string must match the regular expression. See the tips on defining regular expressions.
required {name:required} Rick Used to force non-parameter values ​​in the URL generation process

2. Unified routing prefix

In the first section, we introduced how to use RouteAttribute to mark routing information for methods in the controller. Sometimes there will be such a problem, there may be multiple methods (Action) in a controller method. Under normal circumstances, we require that the request processed by a controller should have a uniform prefix (or called URL directory).

So, in this case, we still continue to use RouteAttribute, but the difference is that this time directly mark on the controller class:

[Route("/Route")]
public class RouteCtrTestController: Controller
{
}

At this time, if RouteAttribute is added to the method, if the route information set does not / start at the beginning, the route configuration of the Action will be added to the back of the Controller. If it / starts with, it means that the route is the root route.

If RouteAttribute is not set, it means that the current method is the method of processing the route configured by the controller.

If multiple RouteAttributes are not set in a controller, an error will occur.

The sample code is as follows:

[Route("/Route")]
public class RouteCtrTestController: Controller
{
   public int temp{get;set;}
   public IActionResult Index(int temp)
   {
       return Content($"你好{temp}");
   }
   [Route("Demo")]
   public IActionResult Demo()
   {
       return Content($"你好 Demo");
   }
}

2. Summary

Today's content is relatively short. Here are some alternative uses of routing. It is enough for friends to have an understanding of this. The next article will come to the view, and start preparing to lead everyone to do a small project.


Guess you like

Origin blog.51cto.com/15060511/2639820