Filter
- 专用于 MVC
- 可以在 MVC 的请求管道里添加逻辑
- 之前、之后
- Cross-cutting concerns(贯穿特性)
- 避免代码重复
- 常用场景
- 授权
- 需要 HTTPS
注:Filter 是专用于 MVC 管道的,不同于之前讲的 ASP.NET Core 的管道。
MVC 管道:
Filter 种类:
- 授权
- 资源
- Action
- 异常
-
实现 Filter
IFilterMetadata
- IAuthorizationFilter, IAsyncAuthorizationFilter
- IResourceFilter(这几个也都有异步版本)
- IActionFilter
- IExceptionFilter
- IResultFilter
同步版:
public class LogResourceFilter : Attribute, IResourceFilter
{
public void OnResourceExecuting(ResourceExecutingContext context)
{
Console.WriteLine("Executing Resource Filter!");
}
public void OnResourceExecuted(ResourceExecutedContext context)
{
Console.WriteLine("Executed Resource Filter...");
}
}
异步版:
public class LogAsyncResourceFilter : Attribute, IAsyncResourceFilter
{
public async Task OnResourceExecutionAsync(
ResourceExecutingContext context,
ResourceExecutionDelegate next)
{
Console.WriteLine("Executing Resource Filter!");
var executedContext = await next();
Console.WriteLine("Executed Resource Filter...");
}
}
应用 Filter
- Action:通过特性标注
- Controller:通过特性标注
- 全局:通过 Startup 配置
配置全局 Filter:
services.AddMvc(options =>
{
options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
//options.Filters.Add(new LogResourceFilter());
//options.Filters.Add(typeof(LogAsyncResourceFilter));
options.Filters.Add<LogResourceFilter>();
});
效果:
几种 Filter 的执行顺序: