5

I am trying to set the Authorize for my controllers can do the following:

[Authorize(Roles = "Approver")]

How ever the names of the roles are held in the database, and therefore I would like to try and do the following:

[Authorize(Roles = Settings.Instance.RoleEmployee)]

but I get the following error:

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

Any way around this?

Aaron Hudon
  • 4,458
  • 3
  • 46
  • 54
Coppermill
  • 6,508
  • 13
  • 65
  • 91

3 Answers3

1
Community
  • 1
  • 1
eu-ge-ne
  • 27,703
  • 6
  • 70
  • 62
  • Both those links imply it's very difficult or impossible. it's relatively easy (5 total lines) to do this by creating your own authorization attribute (e.g. [AuthorizeApprover]) and using that instead. Not very scalable, though. – James S Jul 29 '09 at 12:44
0

If an "Employee" is a known role, then define this string constant in your application, and ensure the a role stored in the database can be mapped to this value when required.

Aaron Hudon
  • 4,458
  • 3
  • 46
  • 54
0
public class UniqueAttribute : ValidationAttribute
{        
    public string Identifier { get; set; }

    public override bool IsValid(object value)
    {          
        // Get property value
        PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
        string identifierValue = properties.Find(this.Identifier,     true).GetValue(value).ToString();
    }
}

You will get value of any property like this above

   [UniqueAttribute(Identifier = "Id")]
Aaron Hudon
  • 4,458
  • 3
  • 46
  • 54
Kuttan Sujith
  • 7,811
  • 18
  • 63
  • 92