X

Disable browser cache in asp mvc

ASP.NET-MVC

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

 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 🙂

[NoCache]
public BaseController: Controller
Categories: ASP .NET aspmvc
Taswar Bhatti:

View Comments (1)

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

Related Post