我想知道如何在 OnActionExecuting
覆盖方法中检查 Controller 方法是否具有特定属性,例如 AllowAnonymous
。
我试过这个:
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/