Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In what order are filters executed in asp.net mvc

In MVC we can decorate action methods with different filters like

[HttpPost] [Authorize] public ActionResult mymethod(){} 

HttpPost derives from MethodSelectorAttribute (probably indirectly) and the Authorize attribute inherits from ActionFilterAttribute.

My question is: in which order are they executed in the MVC request pipeline? I tried to go search in MVC source code but failed to find the relevant code bits.

like image 616
Muhammad Adeel Zahid Avatar asked Jul 03 '11 08:07

Muhammad Adeel Zahid


People also ask

Which filter is executed first in ASP.NET MVC?

in the request life cycle, after the URL Routing module has selected the route and controller have been initialized, the first thing that kicks off in the Action method execution is Authentication Filter.

What is the order in which the action filters are executed?

Filters execute in this order: Authorization filters. Action filters. Response/Result filters.

Which filter is executed first in asp net?

Filters run in the following order: Authorization filters. Action filters. Response filters.

Which filter will execute last in MVC?

Exception Filters − Exception filters are the last type of filter to run. You can use an exception filter to handle errors raised by either your controller actions or controller action results.


2 Answers

Filters run in the following order:

  1. Authorization filters
  2. Action filters
  3. Response filters
  4. Exception filters

For example, authorization filters run first and exception filters run last. Within each filter type, the Order value specifies the run order. Within each filter type and order, the Scope enumeration value specifies the order for filters. This enumeration defines the following filter scope values (in the order in which they run):

  1. First
  2. Global
  3. Controller
  4. Action
  5. Last

Extracted from MSDN

like image 70
Eranga Avatar answered Oct 17 '22 02:10

Eranga


To save you some time, this is how you set the order:

[MyCustomContextFilter(Order=1)] 

The index is 0 based, so you can do 0, 1, 2, etc...

It should be noted that just because a filter is on the base class doesn't tell MVC to apply it first :(.

like image 40
ProVega Avatar answered Oct 17 '22 02:10

ProVega