IAsyncResourceFilter

1、新建一个CustomAsyncResourceFilterAttribute类

 1 using Microsoft.AspNetCore.Mvc;
 2 using Microsoft.AspNetCore.Mvc.Filters;
 3 
 4 namespace Project6.Utility.Filters
 5 {
 6     public class CustomAsyncResourceFilterAttribute : Attribute, IAsyncResourceFilter
 7     {
 8         private static Dictionary<string, object> CacheDictionary = new Dictionary<string, object>();
 9         public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next)
10         {
11             Console.WriteLine("Before");
12             string key = context.HttpContext.Request.Path;
13             if (CacheDictionary.ContainsKey(key))
14             {
15                 context.Result = (IActionResult)CacheDictionary[key];
16             }
17             else
18             {
19                 //执行控制器的构造函数和Action方法
20                 ResourceExecutedContext resource = await next.Invoke();
21                 CacheDictionary[key] = resource.Result;
22                 Console.WriteLine("After");
23             }
24         }
25     }
26 }
View Code

2、新一个控制器CustomAsyncResourceController

 1 using Microsoft.AspNetCore.Mvc;
 2 using Project6.Utility.Filters;
 3 
 4 namespace Project6.Controllers
 5 {
 6     public class CustomAsyncResourceController : Controller
 7     {
 8         
 9         public CustomAsyncResourceController()
10         {
11             Console.WriteLine("构造函数被执行");
12         }
13 
14         [CustomAsyncResourceFilter]
15         public IActionResult Index()
16         {
17             ViewBag.Date = DateTime.Now.ToString("yyyyMMdd HH:mm:ss");
18             return View();
19         }
20     }
21 }
View Code

3、对应的视图

1 <h1>控制器的时间:@ViewBag.Date</h1>
2 <h1>视图的时间:@DateTime.Now.ToString("yyyyMMdd HH:mm:ss")</h1>
View Code

4、在各个方法处设置断点,运行程序/CustomAsyncResource

可以发现程序的执行顺序是:

OnResourceExecutionAsync-->

ResourceExecutedContext resource = await next.Invoke();

CustomAsyncResourceController构造函数-->

Action方法--->

ResourceExecutedContext resource = await next.Invoke();之后的代码。

 

当第二次运行的时候,程序运行到context.Result = (IActionResult)CacheDictionary[key];直接返回结果不在执行之后的代码

实际可以运用在整个视图的缓存,避免数据库重复查询

posted @ 2022-05-03 19:55  ziff123  阅读(122)  评论(0)    收藏  举报