Guilherme Oderdenge
Guilherme Oderdenge

Reputation: 5001

Get parameter's value of a Data Annotation

The goal

Get parameter's value of a Data Annotation.

The problem

I don't know the syntax.

The scenario

There is the following controller on my application:

[PermissionsFilter(Roles = "Administrator")]
public ActionResult Index()
{
    return View();
}

And there is the following method on my application:

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

What I need seems to be simple: how do I get the Administrator string on the AuthorizeCore method? Is via httpContext parameter?

Knowledge spotlight

The AuthorizeCore is within of PermissionFilters class that implements AuthorizeAttribute. In other words, I'm overriding the AuthorizeCore method of Authorize attribute to create a new one (PermissionFilters attribute).

Upvotes: 1

Views: 3340

Answers (1)

chris.house.00
chris.house.00

Reputation: 3301

You need to use reflection to get the attribute applied to your controller action. Below is a quick and dirty example of how you could do that:

    private string GetPermissionFilerValue()
    {
        object[] attributes = typeof(YourControllerType).GetType().GetMethod("Index").GetCustomAttributes(typeof (PermissionFilterAttribute));

        return attributes[0].Roles;
    }

Basically you need to get a reference to your controller's type and then from that, get a reference to the method on your controller. Once you have that, in the form a MethodInfo object, you can use GetCustomAttributes to get all custom attributes applied to your method or all custom attributes of a specific type. Once you have your attribute instance you can inspect the Roles property.

As I mentioned, the example above is a very quick and dirty demonstration of how to get an attribute instance for a specific method. You'll likely need to tailor it to fit it into your specific scenario.

Upvotes: 3

Related Questions