Order of Filters

Order of Execution for Action Filters

  1. Authorization Filters: Execute first and are executed before any other filter.

    • Examples: [Authorize], [AllowAnonymous]

  2. 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.

  3. 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.

  4. 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.

  1. 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:

csharpSao chép mã[Authorize]
[CustomActionFilter]
public ActionResult Index()
{
    // Action logic
}

Here's the sequence of execution for these filters:

  1. Authorize filter executes first, performing authentication and authorization checks.

  2. CustomActionFilter executes next, surrounding the action method execution. Its OnActionExecuting method is called before the action method, and its OnActionExecuted method is called after the action method.

  3. The action method executes.

  4. CustomActionFilter's OnActionExecuted 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