Calling
http://foo/home/cachetest
for
[UrlRoute(Path = "home/cachetest")]
[OutputCache(Duration = 10, VaryByParam = "none")]
public ActionResult CacheTest()
{
return Content(DateTime.Now.To开发者_运维技巧String());
}
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?
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");
}
}
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.
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.
精彩评论