【发布时间】:2020-03-16 15:37:41
【问题描述】:
我已经在全球范围内注册了我的操作过滤器
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new MyNewCustomActionFilter());
}
现在我需要在某些方法中跳过此过滤器, 我想要的行为就像 [AllowAnonymous] 怎么办?
【问题讨论】:
我已经在全球范围内注册了我的操作过滤器
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new MyNewCustomActionFilter());
}
现在我需要在某些方法中跳过此过滤器, 我想要的行为就像 [AllowAnonymous] 怎么办?
【问题讨论】:
您需要分两部分执行此操作。首先,实现您的属性类,您将使用它来装饰您希望排除的方法。
[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
}
【讨论】: