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 @   ziff123  阅读(111)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示