Filter生命周期
在 FourthController 控制器新建 Index5 方法,在对应的过滤器中设置断点。
[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme, Policy = "rolePolicy")]
[CustomCacheResourceFilter]
[TypeFilter(typeof(CustomLogActionFilterAttribute))]
[TypeFilter(typeof(CustomResultFilterAttribute))]
[TypeFilter(typeof(CustomAlwaysRunResultFilterAttribute))]
[TypeFilter(typeof(CustomExceptionFilterAttribute))]
public IActionResult Index5()
{
return View();
}
参考之前关于过滤器的文章:
https://blog.csdn.net/nmmking/article/details/139025585https://blog.csdn.net/nmmking/article/details/139025585https://blog.csdn.net/nmmking/article/details/139021374
https://blog.csdn.net/nmmking/article/details/139021374https://blog.csdn.net/nmmking/article/details/139023237
https://blog.csdn.net/nmmking/article/details/139023237https://blog.csdn.net/nmmking/article/details/138615697
https://blog.csdn.net/nmmking/article/details/138615697分别把6个Filter全部注册到某一个方法,访问 FourthController 的 Index5 :
- a.验证权限,进入到Authorization
- b.ResourceFilter 中的--OnResourceExecuting
- c.开始创建控制器实例
- d.ActionFilter 中的--OnActionExecutinge.执行Action方法
- f.ActionFilter 中的--OnActionExecuted
- g.ResultFilter 中的--OnResultExecuting
- h.AlwaysRunResultFilter 中的-OnResultExecuting
- i.渲染视图
- j.AlwaysRunResultFilter 中的OnResultExecuted
- k.ResultFilter 中的--OnResultExecuted
- L.ResourceFilter中的--OnResourceExecuted
多个相同的Filter不同注册效果
分别定义三个Filter采用全局注册、控制器注册、Action注册。
public class CustomActionActionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
Console.WriteLine("CustomControllerActionFilterAttribute.OnActionExecuting");
}
public override void OnActionExecuted(ActionExecutedContext context)
{
Console.WriteLine("CustomControllerActionFilterAttribute.OnActionExecuted");
}
}
public class CustomControllerActionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
Console.WriteLine("CustomControllerActionFilterAttribute.OnActionExecuting");
}
public override void OnActionExecuted(ActionExecutedContext context)
{
Console.WriteLine("CustomControllerActionFilterAttribute.OnActionExecuted");
}
}
public class CustomGlobalActionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
Console.WriteLine("CustomGlobalActionFilterAttribute.OnActionExecuting");
}
public override void OnActionExecuted(ActionExecutedContext context)
{
Console.WriteLine("CustomGlobalActionFilterAttribute.OnActionExecuted");
}
}
以下就是默认执行顺序:
- 1.全局---开始
- 2.控制器----开始
- 3.Action上---开始
- 4.Action被执行
- 5.Action上---结束
- 6.控制器----结束了
- 7.全局结束
可以通过Order 来控制执行顺序,Order的值越小,就越先执行:
[CustomControllerActionFilterAttribute(Order =20)]
[CustomActionActionFilterAttribute(Order =-99)]