This answer says
"They [attributes] are baked into the assembly at compile-time which has very serious implications of how you could set their properties. Only constant (known at compile time) values are accepted."
...so I'm not sure this is possible:
I want to decorate several methods in my code with attributes that check the role of the current user and only allow execution if the role meets a required minimum.
My attribute so far looks like this:
[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
public class PermissionCheckAttribute : Attribute
{
public PermissionsEnum MinRole { get; set; }
}
I plan to use it like so:
[PermissionCheck(MinRole=PermissionsEnum.Manager)]
public string Foo()
{
return "OK"
}
The roles look like this:
public enum PermissionsEnum
{
Employee: 5
Manager: 20
Director: 50
}
My code has a method that always allows me to check the current user and role:
var userRole = GetCurrentUser().Role // returns Employee[5]
My question is WHERE do I put the code to compare the userRole
to the MinRole
passed into my Attribute?
Ideally, the return "OK"
does not happen if the MinRole
is not reached... but do I have to throw
in the role comparison code? How do you handle two different code paths conditionally with Attributes?