我想知道如何在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时,我会超出范围异常。
我该如何检查?
答案 0 :(得分:4)
我根据你的标签假设这是针对.net核心的。 以下是检查自定义属性的示例
var descriptor = (ControllerActionDescriptor) context.ActionDescriptor;
if (descriptor.MethodInfo.GetCustomAttribute<AuthorizeAttribute>() != null) {
//Do something
}