目录一、简介二、IResourceFilter(同步资源缓存)1、定义Filter三、IAsyncResourceFilter(异步资源缓存)四、总结一、简介 在.net core
在.net core 中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可以看到页面值的变化效果,"来自于控制器的结果"的值会一直不变,“来自于页面的结果”随着页面刷新,值会一直变化
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、异步日志
到此这篇关于.Net Core aop之IResourceFilter的具体使用的文章就介绍到这了,更多相关.net Core Aop IResourceFilter内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: .Net Core Aop之IResourceFilter的具体使用
本文链接: https://lsjlt.com/news/139835.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2023-05-21
2023-05-21
2023-05-21
2023-05-21
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0