user3885927
user3885927

Reputation: 3503

How to get the decorator objects from inside the decorated method

In my ASP.NET MVC 4 controller class I have actions that I decorate with CustomAuthorize attribute so the access is restricted to some roles.

I would like to get the roles from inside the action methods and for this I need the CustomAuthorize attribute that the method is decorated with.

How do I do this?

Sample code of what I am trying to do is below:

public class TestController : Controller
{
    // Only the users in viewer and admin roles should do this
    [CustomAuthorize("viewer", "admin")]
    public ActionResult Index()
    {
        //Need CustomAuthorizeAttribute so I get the associated roles
    }
}

CustomAuthorizeAttribute is a subclass of System.Web.Mvc.AuthorizeAttribute.

Upvotes: 0

Views: 2220

Answers (3)

George
George

Reputation: 787

if you want to get attribute from that method you can do this, for example with reflection:

var atrb = typeof(TestController).GetMethod("Index")
             .GetCustomAttributes(typeof(CustomAuthorizeAttribute), true)
             .FirstOrDefault() as CustomAuthorizeAttribute;

or for the current method;

var atrbCurrentMethod = System.Reflection.MethodBase.GetCurrentMethod()
                .GetCustomAttributes(typeof(CustomAuthorizeAttribute), true)
                .FirstOrDefault() as CustomAuthorizeAttribute;

or a more flexible way, if you want to later create a function, as you stated in your comment:

public CustomAuthorizeAttribute GetCustomAuthorizeAttribute() {
            return new StackTrace().GetFrame(1).GetMethod()
                .GetCustomAttributes(typeof(CustomAuthorizeAttribute), true).FirstOrDefault() as CustomAuthorizeAttribute;
        }

Upvotes: 2

Abhinav Galodha
Abhinav Galodha

Reputation: 9888

Why not use Roles.GetRolesForUser(); method to get all Roles user is having ? This should have the same results as you would get from Reflection parsing the attributes value.

Upvotes: 0

tbddeveloper
tbddeveloper

Reputation: 2447

Attributes are not per instance, they are per class so there is no "current" instance of the CustomAuthorizeAttribute. See the documentation on attributes.

https://msdn.microsoft.com/en-us/library/z0w1kczw.aspx

If you need to get the CustomAuthorizeAttribute you can use reflection to get information about the class you're in and then pull the properties of the attribute but I would question why you need to. Is there something specific you want that we can help more with?

Upvotes: 2

Related Questions