views:

451

answers:

2

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?

+1  A: 

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");
        }
    }
dove
Seems possible. But that's not `easily`. Anyway - thanks. ;)
Arnis L.
+1  A: 

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.

çağdaş
Thanks. They should add that to Mvc2. :/
Arnis L.