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

简介: 上一章介绍了经过路由的处理,一个请求找到了具体处理这个请求的EndPoint,并最终执行它的RequestDelegate方法来处理这个Httpcontext。本章继续这个处理进程,按照惯例,依然通过几幅图来聊一聊这个RequestDelegate之后的故事。在此就避免不了的聊到各种Filter,它方便我们在action执行的前后做一些 “小动作”。
  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会按照这样的顺序被执行,如下图

7.png

 图四

可以看出,在上面几个Filter执行之后,ActionFilter的执行比较特殊,它将Action的执行包在了中间,这段逻辑写在了ControllerActionInvoker自己的类中,同样是一个 Task Next 方法被while循环调用,如下

  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);
    }
}

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

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

目录
相关文章
|
17天前
|
数据可视化 网络协议 C#
C#/.NET/.NET Core优秀项目和框架2024年3月简报
公众号每月定期推广和分享的C#/.NET/.NET Core优秀项目和框架(每周至少会推荐两个优秀的项目和框架当然节假日除外),公众号推文中有项目和框架的介绍、功能特点、使用方式以及部分功能截图等(打不开或者打开GitHub很慢的同学可以优先查看公众号推文,文末一定会附带项目和框架源码地址)。注意:排名不分先后,都是十分优秀的开源项目和框架,每周定期更新分享(欢迎关注公众号:追逐时光者,第一时间获取每周精选分享资讯🔔)。
|
3月前
|
开发框架 前端开发 JavaScript
盘点72个ASP.NET Core源码Net爱好者不容错过
盘点72个ASP.NET Core源码Net爱好者不容错过
71 0
|
3月前
|
开发框架 .NET
ASP.NET Core NET7 增加session的方法
ASP.NET Core NET7 增加session的方法
37 0
|
1月前
|
开发框架 人工智能 .NET
C#/.NET/.NET Core拾遗补漏合集(持续更新)
C#/.NET/.NET Core拾遗补漏合集(持续更新)
|
1月前
|
开发框架 中间件 .NET
C# .NET面试系列七:ASP.NET Core
## 第一部分:ASP.NET Core #### 1. 如何在 controller 中注入 service? 在.NET中,在ASP.NET Core应用程序中的Controller中注入服务通常使用<u>依赖注入(Dependency Injection)</u>来实现。以下是一些步骤,说明如何在Controller中注入服务: 1、创建服务 首先,确保你已经在应用程序中注册了服务。这通常在Startup.cs文件的ConfigureServices方法中完成。例如: ```c# services.AddScoped<IMyService, MyService>(); //
63 0
|
2月前
|
开发框架 前端开发 .NET
福利来袭,.NET Core开发5大案例,30w字PDF文档大放送!!!
为了便于大家查找,特将之前开发的.Net Core相关的五大案例整理成文,共计440页,32w字,免费提供给大家,文章底部有PDF下载链接。
35 1
福利来袭,.NET Core开发5大案例,30w字PDF文档大放送!!!
|
2月前
|
算法 BI API
C#/.NET/.NET Core优秀项目和框架2024年1月简报
C#/.NET/.NET Core优秀项目和框架2024年1月简报
|
6月前
|
开发框架 前端开发 .NET
ASP.NET Core 核心特性学习笔记「下」
ASP.NET Core 核心特性学习笔记「下」
|
6月前
|
开发框架 前端开发 中间件
ASP.NET Core 核心特性学习笔记「上」
ASP.NET Core 核心特性学习笔记「上」
|
SQL 机器学习/深度学习 Cloud Native
.NET 云原生架构师训练营(模块二 基础巩固 EF Core 更新和迁移)--学习笔记
- 状态 - 自动变更检测 - 不查询删除和更新 - 并发
225 0
.NET 云原生架构师训练营(模块二 基础巩固 EF Core 更新和迁移)--学习笔记