Asp.net Mvc OutputCache Attribute and Expiration

Call

http://foo/home/cachetest 

for

 [UrlRoute(Path = "home/cachetest")] [OutputCache(Duration = 10, VaryByParam = "none")] public ActionResult CacheTest() { return Content(DateTime.Now.ToString()); } 

will show the same content every 10 seconds no matter how often I refresh the page.

Is it possible to easily add a sliding ending so that it does not change after 10 seconds if I refresh the page?

+7
caching asp.net-mvc
source share
3 answers

I read the source for OutputCacheAttribute and I don't think this is an easy way to do this.

You will most likely need to create your own solution.

+2
source share

Instead of the standard OutputCache, you can create your own cache filter. As shown below, note that a sliding ending can be set here. The caveat is that I did not use this for a sliding expiration, but works well for other things.

 public class CacheFilterAttribute : ActionFilterAttribute { private const int Second = 1; private const int Minute = 60 * Second; private const int Hour = 60 * Minute; public const int SecondsInDay = Hour * 24; /// <summary> /// Gets or sets the cache duration in seconds. /// The default is 10 seconds. /// </summary> /// <value>The cache duration in seconds.</value> public int Duration { get; set; } public int DurationInDays { get { return Duration / SecondsInDay; } set { Duration = value * SecondsInDay; } } public CacheFilterAttribute() { Duration = 10; } public override void OnActionExecuted( ActionExecutedContext filterContext) { if (Duration <= 0) return; HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache; TimeSpan cacheDuration = TimeSpan.FromSeconds(Duration); cache.SetCacheability(HttpCacheability.Public); cache.SetExpires(DateTime.Now.Add(cacheDuration)); cache.SetMaxAge(cacheDuration); cache.SetSlidingExpiration(true); cache.AppendCacheExtension("must-revalidate, proxy-revalidate"); } } 
+7
source share

You can not. The internal Cache class timer runs every 20 seconds. I suggest you try the PCache class in the PokeIn library. You can set up to 6 seconds. In addition, PCache is much faster than the .NET cache class.

+1
source share

All Articles