Asp.net core 检查操作筛选器中的属性
在MVC 5中,您可以在Asp.net core 检查操作筛选器中的属性,asp.net-core,asp.net-core-mvc,Asp.net Core,Asp.net Core Mvc,在MVC 5中,您可以在IActionFilter中执行类似的操作,以检查属性是否已在当前操作(或控制器范围)上声明 因此,如果您的控制器像这样定义属性,那么这是有效的 [CustomAttribute] public ActionResult Everything() { .. } 在ASP.NET Core MVC中(在IActionFiler内部)也可以这样做吗?可以。下面是ASP.NET核心的类似代码 public void OnActionExecuting(ActionExecut
IActionFilter
中执行类似的操作,以检查属性是否已在当前操作(或控制器范围)上声明
因此,如果您的控制器像这样定义属性,那么这是有效的
[CustomAttribute]
public ActionResult Everything()
{ .. }
在ASP.NET Core MVC中(在
IActionFiler
内部)也可以这样做吗?可以。下面是ASP.NET核心的类似代码
public void OnActionExecuting(ActionExecutingContext context)
{
var controllerActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
if (controllerActionDescriptor != null)
{
var isDefined = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
.Any(a => a.GetType().Equals(typeof(CustomAttribute)));
}
}
试一试
如果您不仅需要检查某个方法的属性,还需要检查.NET Core中的整个控制器的属性,下面是我的操作方法:
var controllerActionDescriptor = actionContext.ActionDescriptor as ControllerActionDescriptor;
if (controllerActionDescriptor != null)
{
// Check if the attribute exists on the action method
if (controllerActionDescriptor.MethodInfo?.GetCustomAttributes(inherit: true)?.Any(a => a.GetType().Equals(typeof(CustomAttribute))) ?? false)
return true;
// Check if the attribute exists on the controller
if (controllerActionDescriptor.ControllerTypeInfo?.GetCustomAttributes(typeof(CustomAttribute), true)?.Any() ?? false)
return true;
}
请记住,没有MVC6,只有ASP.NET核心MVC 1.0、1.1和2.0预览版;)啊!我站直了!
if (context.Filters.Any(x => x.GetType() == typeof(Microsoft.AspNetCore.Mvc.Authorization.AllowAnonymousFilter)))
return;
var controllerActionDescriptor = actionContext.ActionDescriptor as ControllerActionDescriptor;
if (controllerActionDescriptor != null)
{
// Check if the attribute exists on the action method
if (controllerActionDescriptor.MethodInfo?.GetCustomAttributes(inherit: true)?.Any(a => a.GetType().Equals(typeof(CustomAttribute))) ?? false)
return true;
// Check if the attribute exists on the controller
if (controllerActionDescriptor.ControllerTypeInfo?.GetCustomAttributes(typeof(CustomAttribute), true)?.Any() ?? false)
return true;
}