The compiler error is quite understandable, you cannot call any method when declaring an attribute (because its value must be known at compile time), but you can get your own custom attribute obtained from AuthorizeAttribute to execute all the necessary logic. Isn't that what we all did to localize NameAttribute and friends before imagining the long-awaited annotations of localization data?
Proof of concept:
class DynamicAuthorizeAttribute : AuthorizeAttribute { protected bool AuthorizeCore(HttpContextBase context) {
And then:
[DynamicAuthorize] public ActionResult Get() {
This is just one of the possible ways: you can put your own logic, or simply update the Roles property and delegate it to the usual logic, simply by calling base.AuthorizeCore(context) . Keep in mind that all of your code here should be thread safe.
If you work with static methods and want to keep this logic inside your controller, you can play to take (for example) something like this:
[DynamicAuthorize(typeof(MyView), nameof(GetRole))]
Please note that you can access the controller and view the names from context.HttpContext.Request.RequestContext.RouteData .
Then call such a static method. Note: if the logic is really complex and changing a lot, you might want to centralize this logic and use other MVC tools to do this.
Adriano repetti
source share