Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access a Method's Attribute from OnActionExecuting

I was wondering how can I check if a Controller Method has a certain attribute, for example AllowAnonymous, inside OnActionExecuting override method.

I've tried with this:

var methodAttr = Attribute.GetCustomAttribute(context.ActionDescriptor.GetType(), typeof(AuthorizeAttribute));

But I always get a Null value.

Tried also with this:

MethodBase method = MethodBase.GetCurrentMethod();
AuthorizeAttribute methodAttr = (AuthorizeAttribute)method.GetCustomAttributes(typeof(AuthorizeAttribute), true)[0];

But when there is not AuthorizeAttribute I get an out of range exception.

How can I do this check?

like image 698
Santa Cloud Avatar asked Apr 06 '26 03:04

Santa Cloud


1 Answers

I'm assuming based on your tags that this is for .net core. Here is an example of checking for a custom attribute

var descriptor = (ControllerActionDescriptor) context.ActionDescriptor;
if (descriptor.MethodInfo.GetCustomAttribute<AuthorizeAttribute>() != null) { 
    //Do something
}
like image 114
hawkstrider Avatar answered Apr 08 '26 16:04

hawkstrider