[Asp.Net Core]Filter的生效范围和执行顺序

Posted 厦门德仔

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Asp.Net Core]Filter的生效范围和执行顺序相关的知识,希望对你有一定的参考价值。

Filter的生效范围和执行顺序

1.标记在Action上,就只对当前Action生效

2.标记在Controller上,就对Controller上中的所有Action生效

3.全局注册,对于当前整个项目中的Action都生效,在ConfigureServices中增加以下代码即可

如果有三个actionFilter,分别注册全局,控制器、Action;执行顺序如何呢?
定义三个ActionFilter,分别注册全局,控制器,Action
执行顺序如下:
1.控制器实例化
2.全局注册的Filter-OnActionExecuting
3.控制器注册的Filter-OnActionExecuting

            services.AddMvc(option=> 
                //option.Filters.Add<CustomActionFilterAttribute>();
                option.Filters.Add<CustomGlobalActionFilterAtrribute>();
            );

4.Actioin注册的Filter-OnActionExecuting
5.执行Action内部的逻辑算计
6.Action注册的Filter-OnActionExecuted
7.控制器注册的Filter-OnActionExecuted
8.全局注册的Filter-OnActionExecuted
俄罗斯套娃~
执行顺序不能改吗? 能改,在注册Filter的时候,指定Order的值,执行顺序,按照Order的值,从小到大执行;例如:[CustomActionActionFilterAtrribute(Order = -1)]
Filter:

    public class CustomGlobalActionFilterAtrribute : ActionFilterAttribute
    
        public override void OnActionExecuting(ActionExecutingContext context)
        
            Console.WriteLine("CustomGlobalActionFilterAtrribute.OnActionExecuting");
        

        public override void OnActionExecuted(ActionExecutedContext context)
        
            Console.WriteLine("CustomGlobalActionFilterAtrribute.OnActionExecuted");
        
    


    public class CustomControllerActionFilterAtrribute : ActionFilterAttribute
    
        public override void OnActionExecuting(ActionExecutingContext context)
        
            Console.WriteLine("CustomControllerActionFilterAtrribute.OnActionExecuting");
        

        public override void OnActionExecuted(ActionExecutedContext context)
        
            Console.WriteLine("CustomControllerActionFilterAtrribute.OnActionExecuted");
        
    

    public class CustomActionActionFilterAtrribute : ActionFilterAttribute
    
        public override void OnActionExecuting(ActionExecutingContext context)
        
            Console.WriteLine("CustomActionActionFilterAtrribute.OnActionExecuting");
        

        public override void OnActionExecuted(ActionExecutedContext context)
        
            Console.WriteLine("CustomActionActionFilterAtrribute.OnActionExecuted");
        
    

测试

以上是关于[Asp.Net Core]Filter的生效范围和执行顺序的主要内容,如果未能解决你的问题,请参考以下文章

asp.net core系列 68 Filter管道过滤器

asp.net core系列 68 Filter管道过滤器

[Asp.Net Core]Filter的多种注册

ASP.NET Core Filter与IOC的羁绊

ASP.NET Core Filter与IOC的羁绊

ASP.NET Core MVC 2.x 全面教程_ASP.NET Core MVC 25. 过滤器