【问题标题】:How to skip global actionfilter from specific methos如何从特定方法中跳过全局动作过滤器
【发布时间】:2020-03-16 15:37:41
【问题描述】:

我已经在全球范围内注册了我的操作过滤器

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new MyNewCustomActionFilter());
}

现在我需要在某些方法中跳过此过滤器, 我想要的行为就像 [AllowAnonymous] 怎么办?

【问题讨论】:

    标签: c# webapi2


    【解决方案1】:

    您需要分两部分执行此操作。首先,实现您的属性类,您将使用它来装饰您希望排除的方法。

    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
    public class ExcludeAttribute : Attribute
    {
    }
    

    然后,在您的 IActionFilter 实现的 ExecuteActionFilterAsync 方法中,检查被调用的操作是否使用此方法进行修饰。

    public Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
    {
        var excludeAttr = actionContext.ActionDescriptor.GetCustomAttributes<ExcludeAttribute>().SingleOrDefault();
    
        if (excludeAttr != null) // Exclude attribute found; short-circuit this filter
            return continuation();
    
        ... // Execute filter otherwise
    }
    

    【讨论】:

      猜你喜欢
      • 2012-10-05
      • 1970-01-01
      • 2021-07-27
      • 2013-09-29
      • 2016-11-21
      • 1970-01-01
      • 2021-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多