Search code examples
c#custom-attributes

Can I use an enum value in a C# attribute value?


Suppose I have an enum as follows...

public enum Permissions {
  CanAddCustomers,
  CanEditCustomers,
  CanDeleteCustomers,
}

I would like to be able to use this as follows...

[Authorize(Policy = Permissions.CanAddCustomers)]

That's an ASP.NET Core attribute but I don't think that's relevant, as the question applies to any attribute.

Can this be done? Do I need to define my own attribute, possibly inheriting from Authorize? Not sure how I'd do that, so any pointers would be appreciated.


Solution

  • You can create your own attribute like this...

    public class AuthoriseByPermissionAttribute : AuthorizeAttribute {
      public AuthoriseByPermissionAttribute(params Permissions[] permissions) =>
        Policy = permissions.Select(r => r.ToString()).JoinStr();
    }
    

    Then you should be able to use it like this...

    [AuthoriseByPermission(Permissions.CanAddCustomers,Permissions.CanEditCustomers)]