我想知道如何在AllowAnonymous覆盖方法内检查Controller方法是否具有特定属性,例如OnActionExecuting

我已经试过了:

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


但是我总是得到一个Null值。

也尝试过这个:

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


但是,当没有AuthorizeAttribute时,我得到了超出范围的异常。

我该如何检查?

最佳答案

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

var descriptor = (ControllerActionDescriptor) context.ActionDescriptor;
if (descriptor.MethodInfo.GetCustomAttribute<AuthorizeAttribute>() != null) {
    //Do something
}

关于c# - 从OnActionExecuting访问方法的属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50332280/

10-11 05:59