【问题标题】:Checking for an attribute in an action filter检查操作过滤器中的属性
【发布时间】:2017-05-26 10:33:40
【问题描述】:

在 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 内)?

【问题讨论】:

  • 请记住,没有 MVC6,只有 ASP.NET Core MVC 1.0、1.1 和 2.0 预览版;)
  • 啊!我的立场是正确的!

标签: asp.net-core asp.net-core-mvc


【解决方案1】:

是的,你可以做到。这是 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)));
    }
}

【讨论】:

【解决方案2】:

如果您需要检查属性,不仅是方法,还需要 .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;
}

【讨论】:

    【解决方案3】:

    试试

    if (context.Filters.Any(x => x.GetType() == typeof(Microsoft.AspNetCore.Mvc.Authorization.AllowAnonymousFilter)))
                return;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-18
      • 2011-11-17
      • 1970-01-01
      • 2017-03-24
      • 2015-10-15
      相关资源
      最近更新 更多