Filter pipeline in ASP.NET Core

08 Jun 2021 , 2660 words

This amazing flow chart showing the execution flow of filters in ASP.NET Core is from Andrew Lock’s book ASP.NET Core in Action (2nd Edition), so is the summary down below. I find then super helpful so I’ll keep them as a reference. Please do refer to the book for details.

filters

  • Resource, action, and result filters run twice in the pipeline: an *Executing method on the way in and an *Executed method on the way out. Page filters run three times: after page handler selection, and before and after page handler execution.
  • Authorization and exception filters only run once as part of the pipeline; they don’t run after a response has been generated.
  • Within a given stage, global-scoped filters run first, then controller-scoped, and finally, action-scoped. You can also override the default order by implementing the IOrderedFilter interface. Filters will run from lowest to highest Order and use scope to break ties.
  • Authorization filters run first in the pipeline and control access to APIs. ASP.NET Core includes an [Authorization] attribute that you can apply to action methods so that only logged-in users can execute the action.
  • Resource filters run after authorization filters, and again after an IActionResult has been executed. They can be used to short-circuit the pipeline, so that an action method is never executed. They can also be used to customize the model-binding process for an action method.
  • Action filters run after model binding has occurred, just before an action method executes. They also run after the action method has executed. They can be used to extract common code out of an action method to prevent duplication. They don’t execute for Razor Pages, only for MVC controllers.
  • Page filters run three times: after page handler selection, after model binding, and after the page handler method executes. You can use page filters for similar purposes as action filters. Page filters only execute for Razor Pages; they don’t run for MVC controllers.
  • Exception filters execute after action and page filters, when an action method or page handler has thrown an exception. They can be used to provide custom error handling specific to the action executed.
  • Result filters run just before and after an IActionResult is executed. You can use them to control how the action result is executed, or to completely change the action result that will be executed.
  • Result filters aren’t executed when you short-circuit the pipeline using authorization, resource, or exception filters. You can ensure result filters also run for these short-circuit cases by implementing a result filter as IAlwaysRunResultFilter or IAsyncAlwaysRunResultFilter.