简体   繁体   English

在自定义ActionFilter中缓存

[英]Caching in custom ActionFilter

I would like to be able to specify a cache duration on my own action filter's OnActionExecuting method. 我希望能够在自己的动作过滤器的OnActionExecuting方法上指定缓存持续时间。

Whilst I was able to decorate my method with the built-in System.Web.Mvc.OutputCacheAttribute attribute it didn't work. 虽然我可以使用内置的System.Web.Mvc.OutputCacheAttribute属性来装饰我的方法,但是它不起作用。 I take it the use-case for these is purely in a controller's action methods. 我认为这些用例纯粹是在控制器的操作方法中。

[OutputCache(Duration = 300)]
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
  //some code here
}

So in terms of caching within a custom action filter, what are the best practices? 因此,就自定义操作筛选器中的缓存而言,最佳实践是什么?

I don't think there is anything out-of-the-box in ASP.NET MVC for this. 我认为ASP.NET MVC中没有开箱即用的功能。 You can use System.Web.Caching.Cache class and develop your own solution. 您可以使用System.Web.Caching.Cache类并开发自己的解决方案。

var cache = new Cache();

// Set cache value: 
cache.Add("YourKey", "YourData", null, DateTime.Now.AddSeconds(300), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);

// Get cache value:
var value = cache["YourKey"];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM