Asp.net Mvc 的 OutputCache 特性和滑动过期

7

调用

http://foo/home/cachetest

对于

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

无论我多频繁地刷新页面,都会每隔10秒显示相同的内容。

如果我在刷新页面后希望内容不再在10秒后更改,是否可以轻松添加滑动过期?

3个回答

7

您可以创建自定义缓存过滤器,而不是使用默认的OutputCache。像下面这样,注意滑动过期时间可以在此设置。请注意,我尚未将其用于滑动过期,但对其他事情效果很好。

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");
        }
    }

2

我一直在阅读OutputCacheAttribute的源代码,但我认为没有一个简单的方法来做到这一点。

你很可能需要创建自己的解决方案。


谢谢。他们应该将这个添加到Mvc2中。:/ - Arnis Lapsa

1

不行。Cache类的内部计时器每20秒旋转一次。我建议您尝试PokeIn库下的PCache类。您可以将其设置为最低6秒。此外,与.NET缓存类相比,PCache速度更快。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接