I'm working with existing code for an asp.net web page in which the methods in the controllers are restricted according to the role the user is in, as such:
namespace Principal.Controllers
{
[Authorize]
public class MyController: Controller
{
[Authorize(Roles = "Role1,Role2,Role3")]
public method1() {...}
}
}
The problem is the part where the roles allowed are declared:
[Authorize(Roles = "Role1,Role2,Role3")]
I would like to make the string dynamic, so I can return it from a method depending on properties set by an admin, however it keeps giving me weird errors, such as "Error 3 An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type"
Any help would be greatly apreciated.
As you discovered, you can only use constants when defining attributes; this is due to the fact that the attribute is compiled into the code - you cannot use expressions that the compiler does not know at compile time.
What you could do instead, is to create a new attribute inheriting from the AuthorizeAttribute class, and overriding OnAuthorize. Then you can implement your custom role logic here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With