欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ASP.NET Core 2.2 : 十七.Action的执行(Endpoint.RequestDelegate后面的故事)

程序员文章站 2022-06-21 16:08:54
上一章介绍了经过路由的处理,一个请求找到了具体处理这个请求的EndPoint,并最终执行它的RequestDelegate方法来处理这个Httpcontext。本章继续这个处理进程,按照惯例,依然通过几幅图来聊一聊这个RequestDelegate之后的故事。在此就避免不了的聊到各种Filter,它 ......

          上一章介绍了经过路由的处理,一个请求找到了具体处理这个请求的endpoint,并最终执行它的requestdelegate方法来处理这个httpcontext。本章继续这个处理进程,按照惯例,依然通过几幅图来聊一聊这个requestdelegate之后的故事。在此就避免不了的聊到各种filter,它方便我们在action执行的前后做一些 “小动作”。(asp.net core 系列目录

一、概述

          首先看一下requestdelegate这个方法:

requestdelegate requestdelegate = (context) =>
{
    var routedata = context.getroutedata();
    var actioncontext = new actioncontext(context, routedata, action);
    var invoker = _invokerfactory.createinvoker(actioncontext);

    return invoker.invokeasync();
};

          将这个方法的内容分为两部分:

          a. invoker的生成,前三句,通过createinvoker方法生成了一个invoker,它是一个比较复杂的综合体,包含了controller的创建工厂、参数的绑定方法以及本action相关的各种filter的集合等, 也就是说它是前期准备工作阶段,这个阶段扩展开来涉及面比较广,在下文详细描述。  

          b.invoker的执行,最后一句,前面已经万事俱备,准备了好多方法,到此来执行。此时涉及到前面准备的各种方法的执行,各种filter也在此时被执行。

二、invoker的生成

           依照习惯,还是通过流程图来看一看:

                                                                                                     图一()

          首先说一下此图的结构,每个泳道相当于是上一个泳道中的ASP.NET Core 2.2 : 十七.Action的执行(Endpoint.RequestDelegate后面的故事)图标的细化说明,例如第二条泳道是图标标识的方块的明细化。

          a. 泳道一:

                  就是第一节【概述】中描述的的内容,不再赘述。另外提一下本文的核心invoker本质上就是一个controlleractioninvoker,也是图中的actioninvokerprovidercontext.result。

          b.泳道二:即①的详细描述

          ① actioninvokerfactory.createinvoker(actioncontext)

 1 public iactioninvoker createinvoker(actioncontext actioncontext)
 2 {
 3     var context = new actioninvokerprovidercontext(actioncontext);
 4 
 5     foreach (var provider in _actioninvokerproviders)
 6     {
 7         provider.onprovidersexecuting(context);
 8     }
 9 
10     for (var i = _actioninvokerproviders.length - 1; i >= 0; i--)
11     {
12         _actioninvokerproviders[i].onprovidersexecuted(context);
13     }
14 
15     return context.result;
16 }

          本章设计的这部分内容比较常见的一个操作就是context的封装,这从第一个泳道的第一个操作就开始了, 他将httpcontext、routedata,actiondescriptor封装到一起成了一个actioncontext ,而到了这个方法,又将这个actioncontext 封装成了actioninvokerprovidercontext,接下来就是遍历_actioninvokerproviders调用它们的onprovidersexecuting和onprovidersexecuted方法来设置actioninvokerprovidercontext.result,也就是最终的controlleractioninvoker。

          这里说一下_actioninvokerproviders,它的类型是iactioninvokerprovider[],默认情况下包含了两个,分别是controlleractioninvokerprovider和pageactioninvokerprovider,第一个是用于mvc的action的处理,而第二个用于razor pages web的处理。二者的onprovidersexecuting方法都会首先判断当前action是不是自己对应的类型,若不是则直接跳过。二者的onprovidersexecuted方法目前均为空。所以图中和下面关于onprovidersexecuting的描述也仅限于controlleractioninvokerprovider的onprovidersexecuting方法。

          c.泳道三:controlleractioninvokerprovider.onprovidersexecuting(context)

          即泳道二中的③的详细描述

 1 public void onprovidersexecuting(actioninvokerprovidercontext context)
 2 {
 3     if (context.actioncontext.actiondescriptor is controlleractiondescriptor)
 4     {
 5         var controllercontext = new controllercontext(context.actioncontext);
 6         // perf: these are rarely going to be changed, so let's go copy-on-write.
 7         controllercontext.valueproviderfactories = new copyonwritelist<ivalueproviderfactory>(_valueproviderfactories);
 8         controllercontext.modelstate.maxallowederrors = _maxmodelvalidationerrors;
 9 
10         var cacheresult = _controlleractioninvokercache.getcachedresult(controllercontext);
11 
12         var invoker = new controlleractioninvoker(
13             _logger,
14             _diagnosticsource,
15             _mapper,
16             controllercontext,
17             cacheresult.cacheentry,
18             cacheresult.filters);
19 
20         context.result = invoker;
21     }
22 }

         如上文所述,在处理之前,首先就是判断当前action是否是自己对应处理的类型。然后就是继续封装大法,将actioncontext封装成了controllercontext。进而是调用getcachedresult方法读取两个关键内容cacheresult.cacheentry和cacheresult.filters后,将其封装成controlleractioninvoker(⑤)。

          d.第四条泳道:

          对应的是第三条中的④controlleractioninvokercache.getcachedresult(controllercontext);

 1 public (controlleractioninvokercacheentry cacheentry, ifiltermetadata[] filters) getcachedresult(controllercontext controllercontext)
 2 {
 3     var cache = currentcache;
 4     var actiondescriptor = controllercontext.actiondescriptor;
 5 
 6     ifiltermetadata[] filters;
 7     if (!cache.entries.trygetvalue(actiondescriptor, out var cacheentry))
 8     {
 9         var filterfactoryresult = filterfactory.getallfilters(_filterproviders, controllercontext);
10         filters = filterfactoryresult.filters;
11 
12         var parameterdefaultvalues = parameterdefaultvalues
13             .getparameterdefaultvalues(actiondescriptor.methodinfo);
14 
15         var objectmethodexecutor = objectmethodexecutor.create(
16             actiondescriptor.methodinfo,
17             actiondescriptor.controllertypeinfo,
18             parameterdefaultvalues);
19 
20         var controllerfactory = _controllerfactoryprovider.createcontrollerfactory(actiondescriptor);
21         var controllerreleaser = _controllerfactoryprovider.createcontrollerreleaser(actiondescriptor);
22         var propertybinderfactory = controllerbinderdelegateprovider.createbinderdelegate(
23             _parameterbinder,
24             _modelbinderfactory,
25             _modelmetadataprovider,
26             actiondescriptor,
27             _mvcoptions);
28 
29         var actionmethodexecutor = actionmethodexecutor.getexecutor(objectmethodexecutor);
30 
31         cacheentry = new controlleractioninvokercacheentry(
32             filterfactoryresult.cacheablefilters,
33             controllerfactory,
34             controllerreleaser,
35             propertybinderfactory,
36             objectmethodexecutor,
37             actionmethodexecutor);
38         cacheentry = cache.entries.getoradd(actiondescriptor, cacheentry);
39     }
40     else
41     {
42         // filter instances from statically defined filter descriptors + from filter providers
43         filters = filterfactory.createuncachedfilters(_filterproviders, controllercontext, cacheentry.cachedfilters);
44     }
45 
46     return (cacheentry, filters);

           总的来看,本段内容主要是为了组装cacheentry和 filters两个内容,而一个大的 if 体现出这里加入了缓存机制,使系统不必每次都去拼凑这些,提高执行效率。

⑥ifiltermetadata[] filters,它是一个filter的集和,首先调用filterfactory的getallfilters(_filterproviders, controllercontext)方法获取当前action对应的所有filter并对这些filter进行排序(filter部分将在之后章节分享)。

接下来就是组装⑦cacheentry,它的内容比较多,比较重要的几个有:⑧ controllerfactory和controllerreleaser他们的本质都是func<controllercontext, object>,也就是controller的create和release方法。 ⑨propertybinderfactory 是一个用于参数绑定的task,可以说也是一个组装好准备被执行的方法。最后一个⑩actionmethodexecutor也就是执行者,通过actionmethodexecutor.getexecutor(objectmethodexecutor)方法从众多的action执行者(如图二)中找出一个当前action对应的执行者出来。

ASP.NET Core 2.2 : 十七.Action的执行(Endpoint.RequestDelegate后面的故事)

                                                             图二

总结: 本节invoker的生成,总的来说就是一个执行前“万事俱备”的过程,invoker是一个组装起来的集合,它包含一个人(执行者actionmethodexecutor)、n把枪(组装好用于“被执行”的方法例如controllerfactory、controllerreleaser和propertybinderfactory,当然还有个filter的集和)。由此也可以进一步想到,接下来的过程就是这些准备好的内容按照一定的顺序逐步执行的过程。

 二、invoker的执行

invoker的执行也就是invoker.invokeasync(),虽然invoker本质上是controlleractioninvoker,但这个方法写在resourceinvoker类中, controlleractioninvoker : resourceinvoker, iactioninvoker 。

public virtual async task invokeasync()
{
    try
    {
        await invokefilterpipelineasync();
    }
    finally
    {
        releaseresources();
        _logger.executedaction(_actioncontext.actiondescriptor, stopwatch.getelapsedtime());
    }
}

private async task invokefilterpipelineasync()
{
    var next = state.invokebegin;
    var scope = scope.invoker;
    var state = (object)null;

    // `iscompleted` will be set to true when we've reached a terminal state.
    var iscompleted = false;

    while (!iscompleted)
    {
        await next(ref next, ref scope, ref state, ref iscompleted);
    }
}

看似比较简单的两个方法,从invokeasync方法中可以看出来,请求会进入筛选器管道进行处理,也就是 task invokefilterpipelineasync() 方法,借用官方文档中的一个图看一下

ASP.NET Core 2.2 : 十七.Action的执行(Endpoint.RequestDelegate后面的故事)

                                  图三

此图描述了请求经过其他中间件处理后,进入路由处理最终找到了对应的action,最终进入筛选器管道进行处理。而这个处理的核心部分就是方法中的 while (!iscompleted) 循环,它对应的next方法比较长,如下(较长已折叠)

ASP.NET Core 2.2 : 十七.Action的执行(Endpoint.RequestDelegate后面的故事)
  1         private task next(ref state next, ref scope scope, ref object state, ref bool iscompleted)
  2         {
  3             switch (next)
  4             {
  5                 case state.invokebegin:
  6                     {
  7                         goto case state.authorizationbegin;
  8                     }
  9 
 10                 case state.authorizationbegin:
 11                     {
 12                         _cursor.reset();
 13                         goto case state.authorizationnext;
 14                     }
 15 
 16                 case state.authorizationnext:
 17                     {
 18                         var current = _cursor.getnextfilter<iauthorizationfilter, iasyncauthorizationfilter>();
 19                         if (current.filterasync != null)
 20                         {
 21                             if (_authorizationcontext == null)
 22                             {
 23                                 _authorizationcontext = new authorizationfiltercontext(_actioncontext, _filters);
 24                             }
 25 
 26                             state = current.filterasync;
 27                             goto case state.authorizationasyncbegin;
 28                         }
 29                         else if (current.filter != null)
 30                         {
 31                             if (_authorizationcontext == null)
 32                             {
 33                                 _authorizationcontext = new authorizationfiltercontext(_actioncontext, _filters);
 34                             }
 35 
 36                             state = current.filter;
 37                             goto case state.authorizationsync;
 38                         }
 39                         else
 40                         {
 41                             goto case state.authorizationend;
 42                         }
 43                     }
 44 
 45                 case state.authorizationasyncbegin:
 46                     {
 47                         debug.assert(state != null);
 48                         debug.assert(_authorizationcontext != null);
 49 
 50                         var filter = (iasyncauthorizationfilter)state;
 51                         var authorizationcontext = _authorizationcontext;
 52 
 53                         _diagnosticsource.beforeonauthorizationasync(authorizationcontext, filter);
 54                         _logger.beforeexecutingmethodonfilter(
 55                             filtertypeconstants.authorizationfilter,
 56                             nameof(iasyncauthorizationfilter.onauthorizationasync),
 57                             filter);
 58 
 59                         var task = filter.onauthorizationasync(authorizationcontext);
 60                         if (task.status != taskstatus.rantocompletion)
 61                         {
 62                             next = state.authorizationasyncend;
 63                             return task;
 64                         }
 65 
 66                         goto case state.authorizationasyncend;
 67                     }
 68 
 69                 case state.authorizationasyncend:
 70                     {
 71                         debug.assert(state != null);
 72                         debug.assert(_authorizationcontext != null);
 73 
 74                         var filter = (iasyncauthorizationfilter)state;
 75                         var authorizationcontext = _authorizationcontext;
 76 
 77                         _diagnosticsource.afteronauthorizationasync(authorizationcontext, filter);
 78                         _logger.afterexecutingmethodonfilter(
 79                             filtertypeconstants.authorizationfilter,
 80                             nameof(iasyncauthorizationfilter.onauthorizationasync),
 81                             filter);
 82 
 83                         if (authorizationcontext.result != null)
 84                         {
 85                             goto case state.authorizationshortcircuit;
 86                         }
 87 
 88                         goto case state.authorizationnext;
 89                     }
 90 
 91                 case state.authorizationsync:
 92                     {
 93                         debug.assert(state != null);
 94                         debug.assert(_authorizationcontext != null);
 95 
 96                         var filter = (iauthorizationfilter)state;
 97                         var authorizationcontext = _authorizationcontext;
 98 
 99                         _diagnosticsource.beforeonauthorization(authorizationcontext, filter);
100                         _logger.beforeexecutingmethodonfilter(
101                             filtertypeconstants.authorizationfilter,
102                             nameof(iauthorizationfilter.onauthorization),
103                             filter);
104 
105                         filter.onauthorization(authorizationcontext);
106 
107                         _diagnosticsource.afteronauthorization(authorizationcontext, filter);
108                         _logger.afterexecutingmethodonfilter(
109                             filtertypeconstants.authorizationfilter,
110                             nameof(iauthorizationfilter.onauthorization),
111                             filter);
112 
113                         if (authorizationcontext.result != null)
114                         {
115                             goto case state.authorizationshortcircuit;
116                         }
117 
118                         goto case state.authorizationnext;
119                     }
120 
121                 case state.authorizationshortcircuit:
122                     {
123                         debug.assert(state != null);
124                         debug.assert(_authorizationcontext != null);
125                         debug.assert(_authorizationcontext.result != null);
126 
127                         _logger.authorizationfailure((ifiltermetadata)state);
128 
129                         // this is a short-circuit - execute relevant result filters + result and complete this invocation.
130                         iscompleted = true;
131                         _result = _authorizationcontext.result;
132                         return invokealwaysrunresultfilters();
133                     }
134 
135                 case state.authorizationend:
136                     {
137                         goto case state.resourcebegin;
138                     }
139 
140                 case state.resourcebegin:
141                     {
142                         _cursor.reset();
143                         goto case state.resourcenext;
144                     }
145 
146                 case state.resourcenext:
147                     {
148                         var current = _cursor.getnextfilter<iresourcefilter, iasyncresourcefilter>();
149                         if (current.filterasync != null)
150                         {
151                             if (_resourceexecutingcontext == null)
152                             {
153                                 _resourceexecutingcontext = new resourceexecutingcontext(
154                                     _actioncontext,
155                                     _filters,
156                                     _valueproviderfactories);
157                             }
158 
159                             state = current.filterasync;
160                             goto case state.resourceasyncbegin;
161                         }
162                         else if (current.filter != null)
163                         {
164                             if (_resourceexecutingcontext == null)
165                             {
166                                 _resourceexecutingcontext = new resourceexecutingcontext(
167                                     _actioncontext,
168                                     _filters,
169                                     _valueproviderfactories);
170                             }
171 
172                             state = current.filter;
173                             goto case state.resourcesyncbegin;
174                         }
175                         else
176                         {
177                             // all resource filters are currently on the stack - now execute the 'inside'.
178                             goto case state.resourceinside;
179                         }
180                     }
181 
182                 case state.resourceasyncbegin:
183                     {
184                         debug.assert(state != null);
185                         debug.assert(_resourceexecutingcontext != null);
186 
187                         var filter = (iasyncresourcefilter)state;
188                         var resourceexecutingcontext = _resourceexecutingcontext;
189 
190                         _diagnosticsource.beforeonresourceexecution(resourceexecutingcontext, filter);
191                         _logger.beforeexecutingmethodonfilter(
192                             filtertypeconstants.resourcefilter,
193                             nameof(iasyncresourcefilter.onresourceexecutionasync),
194                             filter);
195 
196                         var task = filter.onresourceexecutionasync(resourceexecutingcontext, invokenextresourcefilterawaitedasync);
197                         if (task.status != taskstatus.rantocompletion)
198                         {
199                             next = state.resourceasyncend;
200                             return task;
201                         }
202 
203                         goto case state.resourceasyncend;
204                     }
205 
206                 case state.resourceasyncend:
207                     {
208                         debug.assert(state != null);
209                         debug.assert(_resourceexecutingcontext != null);
210 
211                         var filter = (iasyncresourcefilter)state;
212                         if (_resourceexecutedcontext == null)
213                         {
214                             // if we get here then the filter didn't call 'next' indicating a short circuit.
215                             _resourceexecutedcontext = new resourceexecutedcontext(_resourceexecutingcontext, _filters)
216                             {
217                                 canceled = true,
218                                 result = _resourceexecutingcontext.result,
219                             };
220 
221                             _diagnosticsource.afteronresourceexecution(_resourceexecutedcontext, filter);
222                             _logger.afterexecutingmethodonfilter(
223                                 filtertypeconstants.resourcefilter,
224                                 nameof(iasyncresourcefilter.onresourceexecutionasync),
225                                 filter);
226 
227                             // a filter could complete a task without setting a result
228                             if (_resourceexecutingcontext.result != null)
229                             {
230                                 goto case state.resourceshortcircuit;
231                             }
232                         }
233 
234                         goto case state.resourceend;
235                     }
236 
237                 case state.resourcesyncbegin:
238                     {
239                         debug.assert(state != null);
240                         debug.assert(_resourceexecutingcontext != null);
241 
242                         var filter = (iresourcefilter)state;
243                         var resourceexecutingcontext = _resourceexecutingcontext;
244 
245                         _diagnosticsource.beforeonresourceexecuting(resourceexecutingcontext, filter);
246                         _logger.beforeexecutingmethodonfilter(
247                             filtertypeconstants.resourcefilter,
248                             nameof(iresourcefilter.onresourceexecuting),
249                             filter);
250 
251                         filter.onresourceexecuting(resourceexecutingcontext);
252 
253                         _diagnosticsource.afteronresourceexecuting(resourceexecutingcontext, filter);
254                         _logger.afterexecutingmethodonfilter(
255                             filtertypeconstants.resourcefilter,
256                             nameof(iresourcefilter.onresourceexecuting),
257                             filter);
258 
259                         if (resourceexecutingcontext.result != null)
260                         {
261                             _resourceexecutedcontext = new resourceexecutedcontext(resourceexecutingcontext, _filters)
262                             {
263                                 canceled = true,
264                                 result = _resourceexecutingcontext.result,
265                             };
266 
267                             goto case state.resourceshortcircuit;
268                         }
269 
270                         var task = invokenextresourcefilter();
271                         if (task.status != taskstatus.rantocompletion)
272                         {
273                             next = state.resourcesyncend;
274                             return task;
275                         }
276 
277                         goto case state.resourcesyncend;
278                     }
279 
280                 case state.resourcesyncend:
281                     {
282                         debug.assert(state != null);
283                         debug.assert(_resourceexecutingcontext != null);
284                         debug.assert(_resourceexecutedcontext != null);
285 
286                         var filter = (iresourcefilter)state;
287                         var resourceexecutedcontext = _resourceexecutedcontext;
288 
289                         _diagnosticsource.beforeonresourceexecuted(resourceexecutedcontext, filter);
290                         _logger.beforeexecutingmethodonfilter(
291                             filtertypeconstants.resourcefilter,
292                             nameof(iresourcefilter.onresourceexecuted),
293                             filter);
294 
295                         filter.onresourceexecuted(resourceexecutedcontext);
296 
297                         _diagnosticsource.afteronresourceexecuted(resourceexecutedcontext, filter);
298                         _logger.afterexecutingmethodonfilter(
299                             filtertypeconstants.resourcefilter,
300                             nameof(iresourcefilter.onresourceexecuted),
301                             filter);
302 
303                         goto case state.resourceend;
304                     }
305 
306                 case state.resourceshortcircuit:
307                     {
308                         debug.assert(state != null);
309                         debug.assert(_resourceexecutingcontext != null);
310                         debug.assert(_resourceexecutedcontext != null);
311 
312                         _logger.resourcefiltershortcircuited((ifiltermetadata)state);
313 
314                         _result = _resourceexecutingcontext.result;
315                         var task = invokealwaysrunresultfilters();
316                         if (task.status != taskstatus.rantocompletion)
317                         {
318                             next = state.resourceend;
319                             return task;
320                         }
321 
322                         goto case state.resourceend;
323                     }
324 
325                 case state.resourceinside:
326                     {
327                         goto case state.exceptionbegin;
328                     }
329 
330                 case state.exceptionbegin:
331                     {
332                         _cursor.reset();
333                         goto case state.exceptionnext;
334                     }
335 
336                 case state.exceptionnext:
337                     {
338                         var current = _cursor.getnextfilter<iexceptionfilter, iasyncexceptionfilter>();
339                         if (current.filterasync != null)
340                         {
341                             state = current.filterasync;
342                             goto case state.exceptionasyncbegin;
343                         }
344                         else if (current.filter != null)
345                         {
346                             state = current.filter;
347                             goto case state.exceptionsyncbegin;
348                         }
349                         else if (scope == scope.exception)
350                         {
351                             // all exception filters are on the stack already - so execute the 'inside'.
352                             goto case state.exceptioninside;
353                         }
354                         else
355                         {
356                             // there are no exception filters - so jump right to the action.
357                             debug.assert(scope == scope.invoker || scope == scope.resource);
358                             goto case state.actionbegin;
359                         }
360                     }
361 
362                 case state.exceptionasyncbegin:
363                     {
364                         var task = invokenextexceptionfilterasync();
365                         if (task.status != taskstatus.rantocompletion)
366                         {
367                             next = state.exceptionasyncresume;
368                             return task;
369                         }
370 
371                         goto case state.exceptionasyncresume;
372                     }
373 
374                 case state.exceptionasyncresume:
375                     {
376                         debug.assert(state != null);
377 
378                         var filter = (iasyncexceptionfilter)state;
379                         var exceptioncontext = _exceptioncontext;
380 
381                         // when we get here we're 'unwinding' the stack of exception filters. if we have an unhandled exception,
382                         // we'll call the filter. otherwise there's nothing to do.
383                         if (exceptioncontext?.exception != null && !exceptioncontext.exceptionhandled)
384                         {
385                             _diagnosticsource.beforeonexceptionasync(exceptioncontext, filter);
386                             _logger.beforeexecutingmethodonfilter(
387                                 filtertypeconstants.exceptionfilter,
388                                 nameof(iasyncexceptionfilter.onexceptionasync),
389                                 filter);
390 
391                             var task = filter.onexceptionasync(exceptioncontext);
392                             if (task.status != taskstatus.rantocompletion)
393                             {
394                                 next = state.exceptionasyncend;
395                                 return task;
396                             }
397 
398                             goto case state.exceptionasyncend;
399                         }
400 
401                         goto case state.exceptionend;
402                     }
403 
404                 case state.exceptionasyncend:
405                     {
406                         debug.assert(state != null);
407                         debug.assert(_exceptioncontext != null);
408 
409                         var filter = (iasyncexceptionfilter)state;
410                         var exceptioncontext = _exceptioncontext;
411 
412                         _diagnosticsource.afteronexceptionasync(exceptioncontext, filter);
413                         _logger.afterexecutingmethodonfilter(
414                             filtertypeconstants.exceptionfilter,
415                             nameof(iasyncexceptionfilter.onexceptionasync),
416                             filter);
417 
418                         if (exceptioncontext.exception == null || exceptioncontext.exceptionhandled)
419                         {
420                             // we don't need to do anything to trigger a short circuit. if there's another
421                             // exception filter on the stack it will check the same set of conditions
422                             // and then just skip itself.
423                             _logger.exceptionfiltershortcircuited(filter);
424                         }
425 
426                         goto case state.exceptionend;
427                     }
428 
429                 case state.exceptionsyncbegin:
430                     {
431                         var task = invokenextexceptionfilterasync();
432                         if (task.status != taskstatus.rantocompletion)
433                         {
434                             next = state.exceptionsyncend;
435                             return task;
436                         }
437 
438                         goto case state.exceptionsyncend;
439                     }
440 
441                 case state.exceptionsyncend:
442                     {
443                         debug.assert(state != null);
444 
445                         var filter = (iexceptionfilter)state;
446                         var exceptioncontext = _exceptioncontext;
447 
448                         // when we get here we're 'unwinding' the stack of exception filters. if we have an unhandled exception,
449                         // we'll call the filter. otherwise there's nothing to do.
450                         if (exceptioncontext?.exception != null && !exceptioncontext.exceptionhandled)
451                         {
452                             _diagnosticsource.beforeonexception(exceptioncontext, filter);
453                             _logger.beforeexecutingmethodonfilter(
454                                 filtertypeconstants.exceptionfilter,
455                                 nameof(iexceptionfilter.onexception),
456                                 filter);
457 
458                             filter.onexception(exceptioncontext);
459 
460                             _diagnosticsource.afteronexception(exceptioncontext, filter);
461                             _logger.afterexecutingmethodonfilter(
462                                 filtertypeconstants.exceptionfilter,
463                                 nameof(iexceptionfilter.onexception),
464                                 filter);
465 
466                             if (exceptioncontext.exception == null || exceptioncontext.exceptionhandled)
467                             {
468                                 // we don't need to do anything to trigger a short circuit. if there's another
469                                 // exception filter on the stack it will check the same set of conditions
470                                 // and then just skip itself.
471                                 _logger.exceptionfiltershortcircuited(filter);
472                             }
473                         }
474 
475                         goto case state.exceptionend;
476                     }
477 
478                 case state.exceptioninside:
479                     {
480                         goto case state.actionbegin;
481                     }
482 
483                 case state.exceptionhandled:
484                     {
485                         // we arrive in this state when an exception happened, but was handled by exception filters
486                         // either by setting exceptionhandled, or nulling out the exception or setting a result
487                         // on the exceptioncontext.
488                         //
489                         // we need to execute the result (if any) and then exit gracefully which unwinding resource 
490                         // filters.
491 
492                         debug.assert(state != null);
493                         debug.assert(_exceptioncontext != null);
494 
495                         if (_exceptioncontext.result == null)
496                         {
497                             _exceptioncontext.result = new emptyresult();
498                         }
499 
500                         _result = _exceptioncontext.result;
501 
502                         var task = invokealwaysrunresultfilters();
503                         if (task.status != taskstatus.rantocompletion)
504                         {
505                             next = state.resourceinsideend;
506                             return task;
507                         }
508 
509                         goto case state.resourceinsideend;
510                     }
511 
512                 case state.exceptionend:
513                     {
514                         var exceptioncontext = _exceptioncontext;
515 
516                         if (scope == scope.exception)
517                         {
518                             iscompleted = true;
519                             return task.completedtask;
520                         }
521 
522                         if (exceptioncontext != null)
523                         {
524                             if (exceptioncontext.result != null ||
525                                 exceptioncontext.exception == null ||
526                                 exceptioncontext.exceptionhandled)
527                             {
528                                 goto case state.exceptionhandled;
529                             }
530 
531                             rethrow(exceptioncontext);
532                             debug.fail("unreachable");
533                         }
534 
535                         var task = invokeresultfilters();
536                         if (task.status != taskstatus.rantocompletion)
537                         {
538                             next = state.resourceinsideend;
539                             return task;
540                         }
541                         goto case state.resourceinsideend;
542                     }
543 
544                 case state.actionbegin:
545                     {
546                         var task = invokeinnerfilterasync();
547                         if (task.status != taskstatus.rantocompletion)
548                         {
549                             next = state.actionend;
550                             return task;
551                         }
552 
553                         goto case state.actionend;
554                     }
555 
556                 case state.actionend:
557                     {
558                         if (scope == scope.exception)
559                         {
560                             // if we're inside an exception filter, let's allow those filters to 'unwind' before
561                             // the result.
562                             iscompleted = true;
563                             return task.completedtask;
564                         }
565 
566                         debug.assert(scope == scope.invoker || scope == scope.resource);
567                         var task = invokeresultfilters();
568                         if (task.status != taskstatus.rantocompletion)
569                         {
570                             next = state.resourceinsideend;
571                             return task;
572                         }
573                         goto case state.resourceinsideend;
574                     }
575 
576                 case state.resourceinsideend:
577                     {
578                         if (scope == scope.resource)
579                         {
580                             _resourceexecutedcontext = new resourceexecutedcontext(_actioncontext, _filters)
581                             {
582                                 result = _result,
583                             };
584 
585                             goto case state.resourceend;
586                         }
587 
588                         goto case state.invokeend;
589                     }
590 
591                 case state.resourceend:
592                     {
593                         if (scope == scope.resource)
594                         {
595                             iscompleted = true;
596                             return task.completedtask;
597                         }
598 
599                         debug.assert(scope == scope.invoker);
600                         rethrow(_resourceexecutedcontext);
601 
602                         goto case state.invokeend;
603                     }
604 
605                 case state.invokeend:
606                     {
607                         iscompleted = true;
608                         return task.completedtask;
609                     }
610 
611                 default:
612                     throw new invalidoperationexception();
613             }
614         }
view code

从代码可以看出,它是根据状态state进行轮转,而执行顺序是authorization->resource->exception......  也就是说当前action对应的多种类型的filter会按照这样的顺序被执行,如下图

ASP.NET Core 2.2 : 十七.Action的执行(Endpoint.RequestDelegate后面的故事)

            图四

可以看出,在上面几个filter执行之后,actionfilter的执行比较特殊,它将action的执行包在了中间,这段逻辑写在了controlleractioninvoker自己的类中,同样是一个 task next 方法被while循环调用,如下

ASP.NET Core 2.2 : 十七.Action的执行(Endpoint.RequestDelegate后面的故事)
  1 private task next(ref state next, ref scope scope, ref object state, ref bool iscompleted)
  2         {
  3             switch (next)
  4             {
  5                 case state.actionbegin:
  6                     {
  7                         var controllercontext = _controllercontext;
  8 
  9                         _cursor.reset();
 10 
 11                         _instance = _cacheentry.controllerfactory(controllercontext);
 12 
 13                         _arguments = new dictionary<string, object>(stringcomparer.ordinalignorecase);
 14 
 15                         var task = bindargumentsasync();
 16                         if (task.status != taskstatus.rantocompletion)
 17                         {
 18                             next = state.actionnext;
 19                             return task;
 20                         }
 21 
 22                         goto case state.actionnext;
 23                     }
 24 
 25                 case state.actionnext:
 26                     {
 27                         var current = _cursor.getnextfilter<iactionfilter, iasyncactionfilter>();
 28                         if (current.filterasync != null)
 29                         {
 30                             if (_actionexecutingcontext == null)
 31                             {
 32                                 _actionexecutingcontext = new actionexecutingcontext(_controllercontext, _filters, _arguments, _instance);
 33                             }
 34 
 35                             state = current.filterasync;
 36                             goto case state.actionasyncbegin;
 37                         }
 38                         else if (current.filter != null)
 39                         {
 40                             if (_actionexecutingcontext == null)
 41                             {
 42                                 _actionexecutingcontext = new actionexecutingcontext(_controllercontext, _filters, _arguments, _instance);
 43                             }
 44 
 45                             state = current.filter;
 46                             goto case state.actionsyncbegin;
 47                         }
 48                         else
 49                         {
 50                             goto case state.actioninside;
 51                         }
 52                     }
 53 
 54                 case state.actionasyncbegin:
 55                     {
 56                         debug.assert(state != null);
 57                         debug.assert(_actionexecutingcontext != null);
 58 
 59                         var filter = (iasyncactionfilter)state;
 60                         var actionexecutingcontext = _actionexecutingcontext;
 61 
 62                         _diagnosticsource.beforeonactionexecution(actionexecutingcontext, filter);
 63                         _logger.beforeexecutingmethodonfilter(
 64                             mvccoreloggerextensions.actionfilter,
 65                             nameof(iasyncactionfilter.onactionexecutionasync),
 66                             filter);
 67 
 68                         var task = filter.onactionexecutionasync(actionexecutingcontext, invokenextactionfilterawaitedasync);
 69                         if (task.status != taskstatus.rantocompletion)
 70                         {
 71                             next = state.actionasyncend;
 72                             return task;
 73                         }
 74 
 75                         goto case state.actionasyncend;
 76                     }
 77 
 78                 case state.actionasyncend:
 79                     {
 80                         debug.assert(state != null);
 81                         debug.assert(_actionexecutingcontext != null);
 82 
 83                         var filter = (iasyncactionfilter)state;
 84 
 85                         if (_actionexecutedcontext == null)
 86                         {
 87                             // if we get here then the filter didn't call 'next' indicating a short circuit.
 88                             _logger.actionfiltershortcircuited(filter);
 89 
 90                             _actionexecutedcontext = new actionexecutedcontext(
 91                                 _controllercontext,
 92                                 _filters,
 93                                 _instance)
 94                             {
 95                                 canceled = true,
 96                                 result = _actionexecutingcontext.result,
 97                             };
 98                         }
 99 
100                         _diagnosticsource.afteronactionexecution(_actionexecutedcontext, filter);
101                         _logger.afterexecutingmethodonfilter(
102                             mvccoreloggerextensions.actionfilter,
103                             nameof(iasyncactionfilter.onactionexecutionasync),
104                             filter);
105 
106                         goto case state.actionend;
107                     }
108 
109                 case state.actionsyncbegin:
110                     {
111                         debug.assert(state != null);
112                         debug.assert(_actionexecutingcontext != null);
113 
114                         var filter = (iactionfilter)state;
115                         var actionexecutingcontext = _actionexecutingcontext;
116 
117                         _diagnosticsource.beforeonactionexecuting(actionexecutingcontext, filter);
118                         _logger.beforeexecutingmethodonfilter(
119                             mvccoreloggerextensions.actionfilter,
120                             nameof(iactionfilter.onactionexecuting),
121                             filter);
122 
123                         filter.onactionexecuting(actionexecutingcontext);
124 
125                         _diagnosticsource.afteronactionexecuting(actionexecutingcontext, filter);
126                         _logger.afterexecutingmethodonfilter(
127                             mvccoreloggerextensions.actionfilter,
128                             nameof(iactionfilter.onactionexecuting),
129                             filter);
130 
131                         if (actionexecutingcontext.result != null)
132                         {
133                             // short-circuited by setting a result.
134                             _logger.actionfiltershortcircuited(filter);
135 
136                             _actionexecutedcontext = new actionexecutedcontext(
137                                 _actionexecutingcontext,
138                                 _filters,
139                                 _instance)
140                             {
141                                 canceled = true,
142                                 result = _actionexecutingcontext.result,
143                             };
144 
145                             goto case state.actionend;
146                         }
147 
148                         var task = invokenextactionfilterasync();
149                         if (task.status != taskstatus.rantocompletion)
150                         {
151                             next = state.actionsyncend;
152                             return task;
153                         }
154 
155                         goto case state.actionsyncend;
156                     }
157 
158                 case state.actionsyncend:
159                     {
160                         debug.assert(state != null);
161                         debug.assert(_actionexecutingcontext != null);
162                         debug.assert(_actionexecutedcontext != null);
163 
164                         var filter = (iactionfilter)state;
165                         var actionexecutedcontext = _actionexecutedcontext;
166 
167                         _diagnosticsource.beforeonactionexecuted(actionexecutedcontext, filter);
168                         _logger.beforeexecutingmethodonfilter(
169                             mvccoreloggerextensions.actionfilter,
170                             nameof(iactionfilter.onactionexecuted),
171                             filter);
172 
173                         filter.onactionexecuted(actionexecutedcontext);
174 
175                         _diagnosticsource.afteronactionexecuted(actionexecutedcontext, filter);
176                         _logger.afterexecutingmethodonfilter(
177                             mvccoreloggerextensions.actionfilter,
178                             nameof(iactionfilter.onactionexecuted),
179                             filter);
180 
181                         goto case state.actionend;
182                     }
183 
184                 case state.actioninside:
185                     {
186                         var task = invokeactionmethodasync();
187                         if (task.status != taskstatus.rantocompletion)
188                         {
189                             next = state.actionend;
190                             return task;
191                         }
192 
193                         goto case state.actionend;
194                     }
195 
196                 case state.actionend:
197                     {
198                         if (scope == scope.action)
199                         {
200                             if (_actionexecutedcontext == null)
201                             {
202                                 _actionexecutedcontext = new actionexecutedcontext(_controllercontext, _filters, _instance)
203                                 {
204                                     result = _result,
205                                 };
206                             }
207 
208                             iscompleted = true;
209                             return task.completedtask;
210                         }
211 
212                         var actionexecutedcontext = _actionexecutedcontext;
213                         rethrow(actionexecutedcontext);
214 
215                         if (actionexecutedcontext != null)
216                         {
217                             _result = actionexecutedcontext.result;
218                         }
219 
220                         iscompleted = true;
221                         return task.completedtask;
222                     }
223 
224                 default:
225                     throw new invalidoperationexception();
226             }
227         }
view code

而在actionbegin的时候,通过controllerfactory创建了controller并调用 cacheentry.controllerbinderdelegate(_controllercontext, _instance, _arguments) 进行了参数绑定。

然后的顺序是   actionfilter的onactionexecuting方法 ->action的执行->actionfilter的onactionexecuted方法, action的执行如下:

private async task invokeactionmethodasync()
{
    var controllercontext = _controllercontext;
    var objectmethodexecutor = _cacheentry.objectmethodexecutor;
    var controller = _instance;
    var arguments = _arguments;
    var actionmethodexecutor = _cacheentry.actionmethodexecutor;
    var orderedarguments = preparearguments(arguments, objectmethodexecutor);

    var diagnosticsource = _diagnosticsource;
    var logger = _logger;

    iactionresult result = null;
    try
    {
        diagnosticsource.beforeactionmethod(
            controllercontext,
            arguments,
            controller);
        logger.actionmethodexecuting(controllercontext, orderedarguments);
        var stopwatch = valuestopwatch.startnew();
        var actionresultvaluetask = actionmethodexecutor.execute(_mapper, objectmethodexecutor, controller, orderedarguments);
        if (actionresultvaluetask.iscompletedsuccessfully)
        {
            result = actionresultvaluetask.result;
        }
        else
        {
            result = await actionresultvaluetask;
        }

        _result = result;
        logger.actionmethodexecuted(controllercontext, result, stopwatch.getelapsedtime());
    }
    finally
    {
        diagnosticsource.afteractionmethod(
            controllercontext,
            arguments,
            controllercontext,
            result);
    }
}

 

总结: 如上文说的,本节的内容就是将准备阶段组装的多个方法在这里按一定的被逐步的执行(如图四)。

 

大概内容就是这样,详细分析起来涉及细节还有好多,后面的文章会对一些关键内容进行详细分享。