Asp.net Mvc OutputCache attribute and sliding expi

2019-04-06 21:54发布

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?

3条回答
爷、活的狠高调
2楼-- · 2019-04-06 22:28

You can't. Internal timer of Cache class spins every 20 secs. I suggest you to try PCache class under PokeIn library. You can set down to 6 secs on it. Also, PCache far more faster in comparison to .NET cache class.

查看更多
仙女界的扛把子
3楼-- · 2019-04-06 22:31

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.

查看更多
啃猪蹄的小仙女
4楼-- · 2019-04-06 22:45

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");
        }
    }
查看更多
登录 后发表回答