.Net Core Aop之IResourceFilter

SportSky發表於2022-02-20

一、簡介

在.net core 中Filter分為以下六大類:

1、AuthorizeAttribute(許可權驗證)

2、IResourceFilter(資源快取)

3、IActionFilter(執行方法前後的記錄)

4、IResultFilter(結果生成前後擴充套件)

5、IAlwaysRun(響應結果的補充)

6、IExceptionFilter(異常處理)

二、IResourceFilter(同步資源快取)

1、定義Filter

public class CustomerResourceFilterAttribute : Attribute, IResourceFilter
    {
        private static Dictionary<string,object> cacheDic=new Dictionary<string, object>();
        public void OnResourceExecuting(ResourceExecutingContext context)
        {
            var path=context.HttpContext.Request.Path; 
            if (cacheDic.ContainsKey(path))
            {
                context.Result = (IActionResult)cacheDic[path];
            }
            Console.WriteLine("CustomerResourceFilterAttribute.OnResourceExecuting");
        }
        public void OnResourceExecuted(ResourceExecutedContext context)
        {
            var path = context.HttpContext.Request.Path;
            cacheDic[path] = context.Result;
            Console.WriteLine("CustomerResourceFilterAttribute.OnResourceExecuted");
        }

        
    }

2、使用Filter

public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
            Console.WriteLine($"執行 {this.GetType().Name} 建構函式");
        }

        [CustomerResourceFilter]
        public IActionResult Index()
        {
            ViewBag.Data = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            return View();
        }
    }

3、前端頁面程式碼

@{
    ViewData["Title"] = "Home Page";
}


<h3>來自於控制器的結果:@ViewBag.Data</h3>
<h3>來自於頁面的結果:@DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")</h3>

4、頁面效果

按F5可以看到頁面值的變化效果,"來自於控制器的結果"的值會一直不變,“來自於頁面的結果”隨著頁面重新整理,值會一直變化

 

三、IAsyncResourceFilter(非同步資源快取)

 

public class CustomerAsyncResourceFilterAttribute : Attribute, IAsyncResourceFilter
    {
        private static Dictionary<string, object> cacheDic = new Dictionary<string, object>();
        public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next)
        {
            Console.WriteLine("CustomerResourceFilterAttribute.OnResourceExecutionAsync Before");

            var path = context.HttpContext.Request.Path;
            if (cacheDic.ContainsKey(path))
            {
                context.Result = (IActionResult)cacheDic[path];
            }
            else
            {
                ResourceExecutedContext resource =await next.Invoke();
                cacheDic[path] = resource.Result; // 這句話的執行就是去執行控制器的建構函式+Action
                Console.WriteLine("CustomerResourceFilterAttribute.OnResourceExecutionAsync After");
            }
            

        }
    }

 

四、總結

不管是同步還是非同步,他們的執行順序其實都是一樣的,下面是同步和非同步分別列印的日誌記錄:

1、同步日誌

2、非同步日誌

 

相關文章