Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order property of ActionFilter, from lowest to greatest or vice versa?

I defined two ActionFilters:

[DefaultResources(Order = 2)]
[RenderTemplate(Order = 1)]

And to my surprise DefaultResources is executed BEFORE RenderTemplate. But according to MSDN documentation it should work vice versa:

[Filter1(Order = 2)]
[Filter2(Order = 3)]
[Filter3(Order = 1)]
public void Index()
{
    View("Index");
}

In this example, action filters would execute in the following order: Filter3, Filter1, and then Filter2.

I'm using .NET 4. And comparing by method OnActionExecuted. Am I missing something?

like image 250
Jozef Krchňavý Avatar asked May 27 '11 12:05

Jozef Krchňavý


People also ask

What is the sequence of method execution in filter?

Every filter must implement the three methods in the Filter interface: init(), doFilter(), and destroy().

What is the order of the filters that get executed if multiple filters are implemented?

Filters get executed in the following order for an action: Globally Defined Filters -> Controller-specific Filters -> Action-specific Filters.

What is TypeFilterAttribute?

TypeFilterAttribute is similar to ServiceFilterAttribute, but its type isn't resolved directly from the DI container. It instantiates the type by using Microsoft. Extensions. DependencyInjection. ObjectFactory.

How many types of filters are there in MVC?

The ASP.NET MVC framework supports four different types of filters: Authorization filters – Implements the IAuthorizationFilter attribute. Action filters – Implements the IActionFilter attribute. Result filters – Implements the IResultFilter attribute.


2 Answers

Last-in First-out order

This is the answer I was looking for. Order of OnActionExecuted is reversed order of OnActionExecuting...

like image 88
Jozef Krchňavý Avatar answered Sep 25 '22 03:09

Jozef Krchňavý


It all depends on what each filter implements.

If DefaultResource implements OnActionExecuting or OnActionExecuted then it will fire first if RenderTemplate does not.

For more details see:

http://www.gregshackles.com/2010/09/custom-ordering-of-action-filters-in-asp-net-mvc/

and

http://msdn.microsoft.com/en-us/library/dd381609.aspx

"The ASP.NET MVC framework will call the OnActionExecuting method of your action filter before it calls any action method that is marked with your action filter attribute. Similarly, the framework will call the OnActionExecuted method after the action method has finished. "

like image 33
Adam Tuliper Avatar answered Sep 26 '22 03:09

Adam Tuliper