Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net Mvc OutputCache attribute and sliding expiration

Calling

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 for every 10 seconds no matter how often i refresh page.

Is it possible to easily add sliding expiration so it would NOT change after 10 seconds in case i have refreshed the page?

like image 975
Arnis Lapsa Avatar asked Oct 16 '09 09:10

Arnis Lapsa


2 Answers

You could create a custom cache filter instead of default OutputCache one. Like this below, note the sliding expiration could be set here. Caveat in that I have not used this for 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");
        }
    }
like image 182
dove Avatar answered Sep 20 '22 17:09

dove


Been reading the source for the OutputCacheAttribute and I don't think there's an easy way to do this.

You're most likely going to need to create your own solution.

like image 39
Çağdaş Tekin Avatar answered Sep 20 '22 17:09

Çağdaş Tekin