Francis Ducharme
Francis Ducharme

Reputation: 4987

Multiple ActionFilterAttribute order of execution assured?

I just looked into ActionFilters and they are quite useful. Now, I tried having more than one decorating a method, so as to separate the logic. I thought this would be useful.

So here's an example method

[Common.PortalSecurity.Login]
[Common.PortalSecurity.UserRole]
public HttpResponseMessage GetAll(string sessionToken)
{
    return new HttpResponseMessage();
}

This works fine, but it is mandatory that Login should execute before UserRole.

Is it 100% the order of execution will be respected at every request ?

This blog post seems to say it should work.

Any ideas ?

Upvotes: 4

Views: 8061

Answers (2)

Francisco Goldenstein
Francisco Goldenstein

Reputation: 13767

In MVC5 you inherit from ActionFilter and indicate the order (using Order property of ActionFilter) in the custom attribute like this:

[Common.PortalSecurity.Login(Order=1)]
[Common.PortalSecurity.UserRole(Order=2)]  
public HttpResponseMessage GetAll(string sessionToken)
{
    return new HttpResponseMessage();
}

You can get more information at: https://msdn.microsoft.com/en-us/library/system.web.mvc.filterattribute.order(v=vs.118).aspx

Upvotes: 0

Francis Ducharme
Francis Ducharme

Reputation: 4987

I had the solution proposed above working as such:

Your custom attributes have to inherit:

public class LoginAttribute : ActionFilterWithOrderAttribute
{

}

public class UserRoleAttribute : ActionFilterWithOrderAttribute
{

}

And a method wanting to use it should be decorated as:

[Common.PortalSecurity.Login(Order=1)]
[Common.PortalSecurity.UserRole(Order=2)]  
public HttpResponseMessage GetAll(string sessionToken)
{
    return new HttpResponseMessage();
}

Upvotes: 3

Related Questions