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.
OnActionExecutingmethods of action filters are executed in the order they are registered.Action method execution.
OnActionExecutedmethods of action filters are executed in reverse order.
Result Filters: Execute after the action method but before the action result is executed.
OnResultExecutingmethods of result filters are executed in the order they are registered.Action result execution.
OnResultExecutedmethods 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.
OnExceptionmethods 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:
csharpSao chép mã[Authorize]
[CustomActionFilter]
public ActionResult Index()
{
// Action logic
}Here's the sequence of execution for these filters:
Authorizefilter executes first, performing authentication and authorization checks.CustomActionFilterexecutes next, surrounding the action method execution. ItsOnActionExecutingmethod is called before the action method, and itsOnActionExecutedmethod is called after the action method.The action method executes.
CustomActionFilter'sOnActionExecutedmethod 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