Order of Filters
Order of Execution for Action Filters
Authorization Filters: Execute first and are executed before any other filter.
Examples:
[Authorize]
,[AllowAnonymous]
Action Filters: Execute next, surrounding the action method execution.
OnActionExecuting
methods of action filters are executed in the order they are registered.Action method execution.
OnActionExecuted
methods of action filters are executed in reverse order.
Result Filters: Execute after the action method but before the action result is executed.
OnResultExecuting
methods of result filters are executed in the order they are registered.Action result execution.
OnResultExecuted
methods of result filters are executed in reverse order.
Exception Filters: Execute when an unhandled exception occurs during the execution of an action method or result.
OnException
methods of exception filters are executed in the order they are registered.
Order of Execution for Global Filters
Global filters are registered in the FilterConfig
class and applied to all controllers and actions.
Global Filters: Applied to all actions and controllers, executed before any other filters.
Global filters are executed in the order they are registered.
Example:
Consider a scenario where you have the following filters applied to an action method:
Here's the sequence of execution for these filters:
Authorize
filter executes first, performing authentication and authorization checks.CustomActionFilter
executes next, surrounding the action method execution. ItsOnActionExecuting
method is called before the action method, and itsOnActionExecuted
method is called after the action method.The action method executes.
CustomActionFilter
'sOnActionExecuted
method is called (if no exception occurred during action execution).
Summary
Understanding the order of execution for action filters is crucial for controlling the flow of your application and ensuring that filters are applied in the desired sequence. By applying filters strategically and understanding their execution order, you can implement various cross-cutting concerns such as authorization, logging, caching, and exception handling effectively in your ASP.NET MVC application.
Last updated