Killilea
Killilea

Reputation: 321

MVC: access attribute value in action

MVC 4

I have an action that is decorated with an action filter like this:

    [ViewPermission(PermissionType.GlobalUser)]
    public ActionResult General()
    {

        var permissionType = // trying to access the value passed to the filter ie. PermissionType.GlobalUser value

        return View();
    }

Is there a way to get the properties from the acation filter inside the action itself?

Thanks in advance.

Upvotes: 0

Views: 108

Answers (1)

MichaelDotKnox
MichaelDotKnox

Reputation: 1308

So the quick answer is yes, you can do it doing something like this:

[ViewPermission(PermissionType.GlobalUser)]
public ActionResult General()
    {
        var type = GetType(this);
        var method = type.GetMethod("General");
        var attribute(typeof(ViewPermission));
        var permissionType = attribute.PermissionType;

        return View();
    }

With that said, it is NOT a good idea. Doing reflection is slow. Very slow. You would see performance problems. If you really need to do this, then it is best to figure out a way to do it during initialization of the app, where performance is not as much of a concern.

Hope that helps.

Upvotes: 1

Related Questions