Here is a simple trick on how to disable browser cache in asp mvc application with an attribute.
If you have a base controller just add this to your base and all your request would have Pragma No-Cache
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
public class NoCacheAttribute : ActionFilterAttribute { public override void OnResultExecuting(ResultExecutingContext filterContext) { if (filterContext == null) throw new ArgumentNullException("filterContext"); var cache = GetCache(filterContext); cache.SetExpires(DateTime.UtcNow.AddDays(-1)); cache.SetValidUntilExpires(false); cache.SetRevalidation(HttpCacheRevalidation.AllCaches); cache.SetCacheability(HttpCacheability.NoCache); cache.SetNoStore(); base.OnResultExecuting(filterContext); } protected virtual HttpCachePolicyBase GetCache(ResultExecutingContext filterContext) { return filterContext.HttpContext.Response.Cache; } } } |
Simply add this to your base controller, and you are done 🙂
1 2 |
[NoCache] public BaseController: Controller |
This solution really helped me for a particular scenario, where I didn’t want the browser to cache the data.