2

我想知道如何检查控制器方法是否具有某个属性,例如AllowAnonymous,在OnActionExecuting覆盖方法中。

我试过这个:

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

但我总是得到一个空值。

也试过这个:

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

但是当没有 AuthorizeAttribute 我得到一个超出范围的异常。

我该怎么做这个检查?

4

1 回答 1

4

我根据您的标签假设这是针对 .net 核心的。这是检查自定义属性的示例

var descriptor = (ControllerActionDescriptor) context.ActionDescriptor;
if (descriptor.MethodInfo.GetCustomAttribute<AuthorizeAttribute>() != null) { 
    //Do something
}
于 2018-05-14T14:08:34.830 回答