My web app (in Blazor) is handling roles authorizations this way:Headers of the Blazor page (razor file):
@attribute [AuthorizeRoles(ERole.MyRole1, ERole.MyRole2)]
This syntax works fine.
With AuthorizeRoles
being a custom attribute as you have probably seen on many sites.EDIT:It inherits from AuthorizeAttribute to handle enums instead of strings.I find it less error prone:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)] public class AuthorizeRolesAttribute : AuthorizeAttribute { public AuthorizeRolesAttribute(params ERole[] roles) { if (roles.Any(r => r.GetType().BaseType != typeof(Enum))) throw new ArgumentException(null, nameof(roles)); this.Roles = string.Join(",", roles.Select(r => Enum.GetName(r.GetType(), r))); }
(inspired from the net).
However, I wanted to refactor my ERoles
lists into static class to make it easier to maintain when we add a new role.
I wrote it this way:
public static class RessourceAutorisations { public static ERole[] ROLES_USE_CASE1 { get; } = new ERole[] { ERole.Myrole1, ... }; }
And I call it this way:
@attribute [AuthorizeRoles(RessourceAutorisations.ROLES_USE_CASE1 )]
It unfortunately generates a compile error CS0182
An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
Same if I declare it with a variable a readonly property:
public static ERole[] ROLES_USE_CASE1 = new ERole[] { ERole.Myrole1,... };
or
public readonly static ERole[] ROLES_USE_CASE1 { get; } = new ERole[] { ERole.Myrole1,... };
What's wrong?