I got the below compilation error when I added "System.Configuration.ConfigurationManager.AppSettings["ADGroupReader"].ToString()" to the authorize role section header.
In the web.config I have: add key="ADGroupReader" value="Readers DEV"
Compilation error: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
[AuthorizedRedirect]
[Authorize(Roles = System.Configuration.ConfigurationManager.AppSettings["ADGroupReader"].ToString())]
public class HomeController : Controller
{
.....
}
I do not want to hard code the role (Roles="Readers DEV"); I would like to read it from the web.config. How can I do that?
For role-based authorization, the customer is responsible for providing the user ID, any optional attributes, and all mandatory user attributes necessary to define the user to Payment Feature Services. The customer must also define the roles that are assigned to the user.
This attributes tutorial explains attribute parameter restrictions:
Attribute parameters are restricted to constant values of the following types:
- Simple types (bool, byte, char, short, int, long, float, and double)
- string
- System.Type
- enums
- object (The argument to an attribute parameter of type object must be a constant value of one of the above types.)
- One-dimensional arrays of any of the above types
From description above, this assignment is invalid due to existence of ToString
method:
[Authorize(Roles = System.Configuration.ConfigurationManager.AppSettings["ADGroupReader"].ToString())]
As a workaround, you can create a custom AuthorizeAttribute
with predefined Roles
parameter which contains default assignment to Roles
with your AppSettings
:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public CustomAuthorizeAttribute()
{
this.Roles = ConfigurationManager.AppSettings["ADGroupReader"].ToString();
}
// other stuff
}
Usage in controller class:
[AuthorizedRedirect]
[CustomAuthorize]
public class HomeController : Controller
{
.....
}
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