如何从特定方法跳过全局操作过滤器

How to skip global actionfilter from specific methos

我已经在全球注册了我的 actionfilter

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

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

您需要分两部分完成此操作。首先,实现您的属性 class,您将用它装饰您希望排除的方法。

[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
}