ASP.NET Core 2.2 : 十六.扒一扒新的Endpoint路由方案

asp.net core 从2.2版本开始,采用了一个新的名为endpoint的路由方案,与原来的方案在使用上差别不大,但从内部运行方式上来说,差别还是很大的。上一篇详细介绍了原版路由方案的运行机制,本文仍然通过一幅图来了解一下新版的运行机制,最后再总结一下二者的异同点。(asp.net core 系列目录

一、概述

       此方案从2.2版本开始,被称作终结点路由(下文以“新版”称呼),它是默认开启的,若想采用原来的方案(<=2.1,下文以原版称呼),可以在addmvc的时候进行设置

services.addmvc(option=>option.enableendpointrouting = false).setcompatibilityversion(compatibilityversion.version_2_2);

enableendpointrouting 默认为true,也就是启用新的endpoint方案,设置为false则采用旧版(<=2.1)的路由方案。

        在配置方法上来说,系统仍然采用在startup中的use.mvc()中配置,而实际上内部的处理中间件已由原来的routermiddleware改为endpointmiddleware和endpointroutingmiddleware两个中间件处理,下面依旧通过一幅图来详细看一下:

 二、流程及解析

                                                                            图一

为了方便查看,依然对几个“重点对象”做了颜色标识(点击图片可以看大图):

      1. 路由的初始化配置(图的前两个泳道) 

    ①  一切依然是从startup开始,而且和旧版一样,是通过usemvc方法进行配置,传入routes.maproute(...)这样的一个或多个配置, 不做赘述。
    下面着重说一下后面的流程,看一下mvcapplicationbuilderextensions中的usemvc方法:
 1 public static iapplicationbuilder usemvc(
 2     this iapplicationbuilder app,
 3     action<iroutebuilder> configureroutes)
 4 {
 5 //此处各种验证,略。。
 6     var options = app.applicationservices.getrequiredservice<ioptions<mvcoptions>>();
 7     if (options.value.enableendpointrouting)
 8     {
 9         var mvcendpointdatasource = app.applicationservices
10             .getrequiredservice<ienumerable<endpointdatasource>>()
11             .oftype<mvcendpointdatasource>()
12             .first();
13         var parameterpolicyfactory = app.applicationservices
14             .getrequiredservice<parameterpolicyfactory>();
15 
16         var endpointroutebuilder = new endpointroutebuilder(app);
17 
18         configureroutes(endpointroutebuilder);
19 
20         foreach (var router in endpointroutebuilder.routes)
21         {
22             // only accept microsoft.aspnetcore.routing.route when converting to endpoint
23             // sub-types could have additional customization that we can't knowingly convert
24             if (router is route route && router.gettype() == typeof(route))
25             {
26                 var endpointinfo = new mvcendpointinfo(
27                     route.name,
28                     route.routetemplate,
29                     route.defaults,
30                     route.constraints.todictionary(kvp => kvp.key, kvp => (object)kvp.value),
31                     route.datatokens,
32                     parameterpolicyfactory);
33              mvcendpointdatasource.conventionalendpointinfos.add(endpointinfo);
34             }
35             else
36             {
37                 throw new invalidoperationexception($"cannot use '{router.gettype().fullname}' with endpoint routing.");
38             }
39         }
40         if (!app.properties.trygetvalue(endpointroutingregisteredkey, out _))
41         {
42             // matching middleware has not been registered yet
43             // for back-compat register middleware so an endpoint is matched and then immediately used
44             app.useendpointrouting();
45         }
46         return app.useendpoint();
47     }
48     else
49     {
50        //旧版路由方案
51     }
52 }

            ② 第6行,这里会获取并判断设置的enableendpointrouting的值,若为false,则采用旧版路由,详见上一篇文章;该值默认为true,即采用新版路由。
            ③ 对应第9行,mvcendpointdatasource在新版路由中是个非常非常重要的角色,在启动初始化阶段,它完成了路由表存储和转换,此处先用颜色重点标记一下,大家记住它,在后面的流程中详细介绍。
            ④ 对应第16行,同旧版的routebuilder一样,这里会new一个 endpointroutebuilder,二者都是一个iroutebuilder,所以也同样调用configureroutes(endpointroutebuilder)方法(也就是startup中的配置)获取了一个route的集合(ilist<irouter>)赋值给endpointroutebuilder.routes,这里有个特别该注意的地方if (router is route route && router.gettype() == typeof(route)) ,也就是这里只接受route类型,终结点路由系统不支持基于 irouter的可扩展性,包括从 route继承。
            ⑤ 对应第20行,这里对刚获取到的endpointroutebuilder.routes进行遍历,转换成了一个mvcendpointinfo的集和,赋值给mvcendpointdatasource.conventionalendpointinfos。
            ⑥ 之后就是向管道塞中间件了,这里的处理中间件由原来的routermiddleware改为endpointmiddleware和endpointroutingmiddleware。

       2.请求的处理(图的后两个泳道)

       请求的处理大部分功能在中间件endpointroutingmiddleware,他有个重要的属性_endpointdatasource保存了上文中初始化阶段生成的mvcendpointdatasource,而中间件endpointmiddleware的功能比较简单,主要是在endpointroutingmiddleware筛选出endpoint之后,调用该endpoint的endpoint.requestdelegate(httpcontext)进行请求处理。
            ⑦ initializeasync()方法主要是用于调用initializecoreasync()创建一个matcher,而通过这个方法的代码可以看出它只是在第一次请求的时候执行一次。

private task<matcher> initializeasync()
{
var initializationtask = _initializationtask;
if (initializationtask != null)
{
return initializationtask;
}

return initializecoreasync();
}

            ⑧ mvcendpointdatasource一个重要的方法updateendpoints(),作用是读取所有action,并将这个action列表与它的conventionalendpointinfos列表(见⑤)进行匹配,最终生成一个新的列表。如下图,我们默认情况下只配置了一个"{controller=home}/{action=index}/{id?}"这样的路由,默认的homecontroller有三个action,添加了一个名为flylolocontroller的controller并添加了一个带属性路由的action,最终生成了7个endpoint,这有点像路由与action的“乘积”。当然,这里只是用默认程序举了个简单的例子,实际项目中可能会有更多的路由模板注册、会有更多的controller和action以及属性路由等。

                                                      图二

具体代码如下:

 1         private void updateendpoints()
 2         {
 3             lock (_lock)
 4             {
 5                 var endpoints = new list<endpoint>();
 6                 stringbuilder patternstringbuilder = null;
 7 
 8                 foreach (var action in _actions.actiondescriptors.items)
 9                 {
10                     if (action.attributerouteinfo == null)
11                     {
12                         // in traditional conventional routing setup, the routes defined by a user have a static order
13                         // defined by how they are added into the list. we would like to maintain the same order when building
14                         // up the endpoints too.
15                         //
16                         // start with an order of '1' for conventional routes as attribute routes have a default order of '0'.
17                         // this is for scenarios dealing with migrating existing router based code to endpoint routing world.
18                         var conventionalrouteorder = 1;
19 
20                         // check each of the conventional patterns to see if the action would be reachable
21                         // if the action and pattern are compatible then create an endpoint with the
22                         // area/controller/action parameter parts replaced with literals
23                         //
24                         // e.g. {controller}/{action} with homecontroller.index and homecontroller.login
25                         // would result in endpoints:
26                         // - home/index
27                         // - home/login
28                         foreach (var endpointinfo in conventionalendpointinfos)
29                         {
30                             // an 'endpointinfo' is applicable if:
31                             // 1. it has a parameter (or default value) for 'required' non-null route value
32                             // 2. it does not have a parameter (or default value) for 'required' null route value
33                             var isapplicable = true;
34                             foreach (var routekey in action.routevalues.keys)
35                             {
36                                 if (!matchroutevalue(action, endpointinfo, routekey))
37                                 {
38                                     isapplicable = false;
39                                     break;
40                                 }
41                             }
42 
43                             if (!isapplicable)
44                             {
45                                 continue;
46                             }
47 
48                             conventionalrouteorder = createendpoints(
49                                 endpoints,
50                                 ref patternstringbuilder,
51                                 action,
52                                 conventionalrouteorder,
53                                 endpointinfo.parsedpattern,
54                                 endpointinfo.mergeddefaults,
55                                 endpointinfo.defaults,
56                                 endpointinfo.name,
57                                 endpointinfo.datatokens,
58                                 endpointinfo.parameterpolicies,
59                                 suppresslinkgeneration: false,
60                                 suppresspathmatching: false);
61                         }
62                     }
63                     else
64                     {
65                         var attributeroutepattern = routepatternfactory.parse(action.attributerouteinfo.template);
66 
67                         createendpoints(
68                             endpoints,
69                             ref patternstringbuilder,
70                             action,
71                             action.attributerouteinfo.order,
72                             attributeroutepattern,
73                             attributeroutepattern.defaults,
74                             noninlinedefaults: null,
75                             action.attributerouteinfo.name,
76                             datatokens: null,
77                             allparameterpolicies: null,
78                             action.attributerouteinfo.suppresslinkgeneration,
79                             action.attributerouteinfo.suppresspathmatching);
80                     }
81                 }
82 
83                 // see comments in defaultactiondescriptorcollectionprovider. these steps are done
84                 // in a specific order to ensure callers always see a consistent state.
85 
86                 // step 1 - capture old token
87                 var oldcancellationtokensource = _cancellationtokensource;
88 
89                 // step 2 - update endpoints
90                 _endpoints = endpoints;
91 
92                 // step 3 - create new change token
93                 _cancellationtokensource = new cancellationtokensource();
94                 _changetoken = new cancellationchangetoken(_cancellationtokensource.token);
95 
96                 // step 4 - trigger old token
97                 oldcancellationtokensource?.cancel();
98             }
99         }

本质就是计算出一个个可能被请求的请求终结点,也就是endpoint。由此可见,如上一篇文章那样想自定义一个handler来处理特殊模板的方式(如 routes.maproute("flylolo/{code}/{name}", myroutehandler.handler);)将被忽略掉,因其无法生成 endpoint,且此种方式完全可以自定义一个中间件来实现,没必要混在路由中。

            ⑨ 就是用上面生成的matcher,携带endpoint列表与请求url做匹配,并将匹配到的endpoint赋值给feature.endpoint。
            ⑩ 获取feature.endpoint,若存在则调用其requestdelegate处理请求httpcontext。

 三、新版与旧版的异同点总结

简要从应用系统启动和请求处理两个阶段对比说一下两个版本的区别:

1.启动阶段:

这个阶段大部分都差不多,都是通过startup的app.usemvc()方法配置一个路由表,一个route的集合routes(ilist<irouter>),然后将其简单转换一下

<=2.1:  将routes转换为routecollection

2.2+ :   将routes转换为list<mvcendpointinfo>

二者区别不大,虽然名字不同,但本质上还是差不多,都仍可理解为route的集合的包装。

2.请求处理阶段:

<=2.1:   1. 将请求的url与routecollection中记录的路由模板进行匹配。

           2. 找到匹配的route之后,再根据这个请求的url判断是否存在对应的controlled和action。

           3. 若以上均通过,则调用route的handler对httpcontext进行处理。

2.2+ :   1. 第一次处理请求时,首先根据启动阶段所配置的路由集合list<mvcendpointinfo>和_actions.actiondescriptors.items(所有的action的信息)做匹配,生成一个列表,这个列表存储了所有可能被匹配的url模板,如图二,这个列表同样是list<mvcendpointinfo>,记录了所有可能的url模式,实际上是列出了一个个可以被访问的详细地址,已经算是最终地址了,即终结点,或许就是为什么叫endpoint路由的原因。

            2.请求的url和这个生成的表做匹配,找到对应的mvcendpointinfo。

            3. 调用被匹配的mvcendpointinfo的requestdelegate方法对请求进行处理。

二者区别就是对于_actions.actiondescriptors.items(所有的action的信息)的匹配上,原版是先根据路由模板匹配后,再根据actiondescriptors判断是否存在对应的controller和action,而新版是先利用了action信息与路由模板匹配,然后再用请求的url进行匹配,由于这样的工作只在第一次请求的时候执行,所以虽然没有做执行效率上的测试,但感觉应该是比之前快的。

本文链接:https://2i3i.com/aspnetcore2_16.html ,转载请注明来源地址。
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇