文章目录
显示
Python微信订餐小程序课程视频
https://edu.csdn.net/course/detail/36074
Python实战量化交易理财系统
https://edu.csdn.net/course/detail/35475
一、简介
在.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 \_logger;
public HomeController(ILogger 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";
}
### 来自于控制器的结果:@ViewBag.Data
### 来自于页面的结果:@DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
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、异步日志
转载请注明:xuhss » .Net Core Aop之IResourceFilter