Search code examples
asp.netasp.net-mvcaction-filter

Caching in custom ActionFilter


I would like to be able to specify a cache duration on my own action filter's OnActionExecuting method.

Whilst I was able to decorate my method with the built-in System.Web.Mvc.OutputCacheAttribute attribute it didn't work. 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?


Solution

  • I don't think there is anything out-of-the-box in ASP.NET MVC for this. You can use System.Web.Caching.Cache class and develop your own solution.

    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"];