0

I am trying to use the Authorize class in my ASP MVC3 app. Unfortunately due to business rules I need to pull the Roles from our web.config, however this is throwing the following exception:

An attribute must be a constant expression, typeof or array creation expression of an attribute parameter type

Here is the code I'm referencing.

[Authorize(Roles = ConfigurationManager.AppSettings.Get("user"))]
public class AdminController : Controller
{

Here is the user section of my web.config

<add key="user" value="SA\\Application.MortalityConcentrationRA.Dev.Users" />
NealR
  • 10,189
  • 61
  • 159
  • 299

2 Answers2

2

Try creating a custom authorize attribute like this:

public class MyAuthorizeAttribute : AuthorizeAttribute
    {
        public MyAuthorizeAttribute()
        {
            this.Roles = ConfigurationManager.AppSettings["user"];
        }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            return base.AuthorizeCore(httpContext);
        }
}

And using it in your controller like this:

[MyAuthorize]
public class HomeController : Controller
{
  //code here
}
HitLikeAHammer
  • 2,679
  • 3
  • 37
  • 53
0

I'm afraid you'll need a custom authorize attribute. I looked around a bit and didn't find any other possible solution. The current attribute is requiring a constant, and I just do not know of a way to have your config.AppSettings[] ever be a constant value (it's pretty much by definition not a constant).

Have a look at this SO post that explains pretty much exactly what you need to do. You question is almost a duplicate of this one (which is good for you, there's already an answer).

Community
  • 1
  • 1
Mike C.
  • 3,024
  • 2
  • 21
  • 18