Disable browser cache in asp mvc

Posted in ASP .NET, aspmvc on July 29th, 2011 by taswar

Here is a simple trick on how to disable browser cache in your asp .net 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

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
 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);
        }
 
        /// <summary>
        /// Get the reponse cache
        /// </summary>
        /// <param name="filterContext"></param>
        /// <returns></returns>
        protected virtual HttpCachePolicyBase GetCache(ResultExecutingContext filterContext)
        {
            return filterContext.HttpContext.Response.Cache;
        }
     }
}

Simply add this to your base controller, and you are done :)

?View Code CSHARP
1
2
[NoCache]
public BaseController: Controller
Share

One Response

  1. Sumit Zitshi Says:

    This solution really helped me for a particular scenario, where I didn’t want the browser to cache the data.

Leave a Comment