NealR
NealR

Reputation: 10679

Error using ConfigurationManager.AppSettings.Get() in ASP MVC3 site

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" />

Upvotes: 0

Views: 1092

Answers (2)

HitLikeAHammer
HitLikeAHammer

Reputation: 2695

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
}

Upvotes: 2

Mike C.
Mike C.

Reputation: 3114

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).

Upvotes: 0

Related Questions