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?
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
}