练习+博客,量化自己的进步!
此博文是参考微软官方文档写的,加上自己的亲自实测,用自己理解的方式整理一下。
Filter筛选器,在Action之前或之后执行的代码!可以用来做授权校验、异常处理、日志记录、缓存、配置等工作。
筛选器的类型有:
- 授权筛选器 校验用户是否登录、是否拥有权限等。
- 资源筛选器
- 操作筛选器
- 异常筛选器 异常处理,可以做一个全局异常捕获,将异常信息在指定的异常页面展示。
- 结果筛选器
筛选器的类型还是挺多的,但它们也是有执行顺序的。
实现
筛选器的实现有两种写法,同步、异步。
同步的:
public class MySampleActionFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
throw new NotImplementedException();
}
public void OnActionExecuted(ActionExecutedContext context)
{
throw new NotImplementedException();
}
}
这是一个同步的写法,继承IActionFilter,是一个操作筛选器,两个方法,OnActionExecting(之前)、OnActionExecuted(之后)。
异步的:
public class MySampleAsyncActionFilter : IAsyncActionFilter
{
// 注意方法为 async
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
// Do something before
// next() 后,才会在Action之后执行代码
var resultContext = await next();
// Do something after
}
}
异步的就是将同步的两个方法合并起来了,异步的next()使用不使用可以灵活决定,格式如上(下面实例的内容将不会再使用异步的)。
- 筛选器可以实现多个类型的接口,如同时实现IActionFilter、IResultFilter.
- 筛选器的同步和异步版本可以同时存在,但运行时只调用一种,只调用异步的,即运行时优先使用异步的版本。
筛选器作用域和执行顺序
筛选器可以作用到Action、Controller或者全局的。
全局筛选器:
services.AddMvc(options=> {
options.Filters.Add(new MySampleActionFilter());
options.Filters.Add(typeof(MySampleActionFilter));
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
这个就是将上面自定已的筛选器添加到全局筛选器的,new、typeof两种写法都可以。在startup.cs文件中添加。
不同作用域的筛选器也有执行顺序:
- 全局的 before
- Controller的before
- Action的before
- Action的after
- Controller的before
- 全局的 after
控制器和Razor页面及筛选器
除了上面三个作用域的筛选器之外,还有这个筛选器:
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public override void OnActionExecuting(ActionExecutingContext context)
{
base.OnActionExecuting(context);
}
public override void OnActionExecuted(ActionExecutedContext context)
{
base.OnActionExecuted(context);
}
}
写在Controller中的筛选器,这个优先级跟高,最先执行此before,最后执行此after。
- HomeController.OnActionExecting