在MVC 5中,您可以在IActionFilter
内执行此类操作,以检查是否已在当前操作(或控制器范围)上声明属性
public void OnActionExecuting(ActionExecutingContext filterContext)
{
// Stolen from System.Web.Mvc.AuthorizeAttribute
var isAttributeDefined = filterContext.ActionDescriptor.IsDefined(typeof(CustomAttribute), true) ||
filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(CustomAttribute), true);
}
因此,如果您的控制器像这样定义属性,则可以正常工作。
[CustomAttribute]
public ActionResult Everything()
{ .. }
是否可以在ASP.NET Core MVC中进行相同的操作(在IActionFiler
内)?
答案 0 :(得分:7)
是的,你可以做到。这是ASP.NET Core的类似代码。
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)));
}
}
答案 1 :(得分:0)
尝试
if (context.Filters.Any(x => x.GetType() == typeof(Microsoft.AspNetCore.Mvc.Authorization.AllowAnonymousFilter)))
return;
答案 2 :(得分:0)
如果需要检查方法的属性,还需要检查.NET Core中整个控制器的属性,这是我的方法:
var controllerActionDescriptor = actionContext.ActionDescriptor作为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;
}