从 OnActionExecuting 访问方法的属性
Access a Method's Attribute from OnActionExecuting
我想知道如何检查控制器方法是否具有某个属性,例如 AllowAnonymous
,在 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
}
我想知道如何检查控制器方法是否具有某个属性,例如 AllowAnonymous
,在 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
}