我已经在全球注册了我的操作过滤器
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new MyNewCustomActionFilter());
}
现在我需要在一些方法中跳过这个过滤器,我想要的行为就像[AllowAnonyment]如何做到?
您需要分两部分来完成。首先,实现您的属性类,用它来装饰要排除的方法。
[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
}