Search code examples
asp.net-mvcaction-filter

Order of AuthorizationFilter applied to a controller/method


if I have two custom implementation of IAuthorizationFilter, and both of them applied to a method in a controller, how do we determine which filter is executed first?

e.g.

Declaration:

public class MyAuthenticationFilter : FilterAttribute, IAuthorizationFilter
public class MyAuthorisationFilter : FilterAttribute, IAuthorizationFilter

Applied:

    [MyAuthorisationFilter(AllowedRoles = "Admin")]
    [MyAuthenticationFilter()]
    public class UsersController : Controller
{
...
}

Through experiments it seems that the Authenication one is executed first just because it is placed nearer to the controller declaration... Can we specify the order or is it a default behaviour?

Thanks!


Solution

  • Use the Order property:

    [MyAuthenticationFilter(Order=1)]
    [MyAuthorisationFilter(AllowedRoles = "Admin",Order=2)]
    public class UsersController : Controller
    {
    ...
    }