当前位置:主页 > 软件编程 > .NET代码 >

.Net Core Aop之IResourceFilter的具体使用

时间:2022-08-23 10:23:02 | 栏目:.NET代码 | 点击:

一、简介

在.net core 中Filter分为以下六大类:

二、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、异步日志

您可能感兴趣的文章:

相关文章