DreamingOfSleep
DreamingOfSleep

Reputation: 1448

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.

Upvotes: 0

Views: 113

Answers (2)

abolfazl  sadeghi
abolfazl sadeghi

Reputation: 2368

You can use two ways

1.Define a attribute

[AttributeUsage(
    AttributeTargets.Method | 
    AttributeTargets.Class, 
    Inherited = true, 
    AllowMultiple = true)]
public class MyAuthorizeAttribute : AuthorizeAttribute
{
    public MyAuthorizeAttribute(params Permissions[] Permissions)
                => this.Policy = string.Join(",", Permissions.Select(r => Enum.GetName(r.GetType(), r)));

}

use


[MyAuthorize( 
new Permissions[] { 
   Permissions.CanAddCustomers, Permissions.CanDeleteCustomers } )]

2.Define a class and use it instead of this name

public static class Policys
{
    public const string CanAddCustomers = "CanAddCustomers";
    public const string CanEditCustomers = "CanEditCustomers";
    public const string CanDeleteCustomers = "CanDeleteCustomers";

}

use

[Authorize(Policy = 
Policys.CanDeleteCustomers + "," + Policys.CanAddCustomers)]

Upvotes: 1

Avrohom Yisroel
Avrohom Yisroel

Reputation: 9440

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)]

Upvotes: 1

Related Questions