Pop
Pop

Reputation: 525

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

I have these two line:

[AccessDeniedAuthorize(new string[] { "MIS", "Test" })]

[AccessDeniedAuthorize(DAL.RoleHandler.GetRolesForTcode("testMenu"))]

But second line has this error:

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

But GetRolesForTcode returns string[] too, why the error?

public class AccessDeniedAuthorizeAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);

        if (filterContext.Result is HttpUnauthorizedResult)
        {
            filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary { { "Controller", "AccessDenied" }, { "Action", "Index" } });
        }
    }

    public AccessDeniedAuthorizeAttribute(string[] roles)
    {
        this.Roles = string.Join(",", roles);
    }
}

public class RoleHandler
{
    public static string[] GetRolesForTcode(string tCode)
    {
        using (var db = new Models.VMIEntities())
        {
            var roles = db.T_Auth_Role_Master
                .Where(role => string.Compare(role.obj, "t_code", StringComparison.OrdinalIgnoreCase) == 0)
                .Where(role => string.Compare(role.authobj_value, tCode, StringComparison.OrdinalIgnoreCase) == 0)
                .Select(role => role.role);
            return roles.ToArray();
        }
    }
}

Upvotes: 1

Views: 3780

Answers (1)

Sweeper
Sweeper

Reputation: 271735

As you have quoted,

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

DAL.RoleHandler.GetRolesForTcode("testMenu") is not any of those things. It is not a constant expression because it can't be evaluated at compile time. Methods are evaluated at run time.

According to the C# language specification section 17.2,

An expression E is an attribute-argument-expression if all of the following statements are true:

  • The type of E is an attribute parameter type (§17.1.3).
  • At compile-time, the value of E can be resolved to one of the following:
    • A constant value.
    • A System.Type object.
    • A one-dimensional array of attribute-argument-expressions.

So that's why the error occurs. You must put a constant expression in there.

Upvotes: 2

Related Questions