asp.net mvc decorate [Authorize()] with multiple enums

Here is a simple and elegant solution which allows you to simply use the following syntax:

[AuthorizeRoles(MyEnum.Admin, MyEnum.Moderator)]

When creating your own attribute, use the params keyword in your constructor:

public class AuthorizeRoles : AuthorizeAttribute
{
    public AuthorizeRoles(params MyEnum[] roles)
    {
        ...
    }
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        ...
    }
}

This will allow you to use the attribute as follows:

[AuthorizeRoles(MyEnum.Admin, MyEnum.Moderator)]
public ActionResult myAction()
{
}

Leave a Comment