I want OutputCache attribute to produce a header with Cache-Control set to public. How do I do that?
1 Answer
Maybe this code for Attribute will help
using System;
using System.Web;
using System.Web.Mvc;
public class CacheFilterAttribute : ActionFilterAttribute {
/// <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 CacheFilterAttribute() {
Duration = 30;
}
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.AppendCacheExtension("must-revalidate, proxy-revalidate");
}
}
and then use [CacheFilter] instead of OutputCache
3 Comments
THX-1138
one important thing OutputCache filter does - is actually caching the response (server side), will this attribute cache the response (so that Action is not executed on every call)?
Vadim Lozinskiy
Hi try
[CacheFilter(Duration = 60, Order = 2)] [OutputCache(Duration = 60, Order = 1)] ta.speot.is
Gets or sets the cache duration in seconds. The default is 10 seconds.
public CacheFilterAttribute() { Duration = 30; }