Disable browser cache for entire ASP.NET website Disable browser cache for entire ASP.NET website asp.net asp.net

Disable browser cache for entire ASP.NET website


Create a class that inherits from IActionFilter.

public class NoCacheAttribute : ActionFilterAttribute{      public override void OnResultExecuting(ResultExecutingContext filterContext)    {        filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));        filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);        filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);        filterContext.HttpContext.Response.Cache.SetNoStore();        base.OnResultExecuting(filterContext);    }}

Then put attributes where needed...

[NoCache][HandleError]public class AccountController : Controller{    [NoCache]    [Authorize]    public ActionResult ChangePassword()    {        return View();    }}


Instead of rolling your own, simply use what's provided for you.

As mentioned previously, do not disable caching for everything. For instance, jQuery scripts used heavily in ASP.NET MVC should be cached. Actually ideally you should be using a CDN for those anyway, but my point is some content should be cached.

What I find works best here rather than sprinkling the [OutputCache] everywhere is to use a class:

[System.Web.Mvc.OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]public class NoCacheController  : Controller{}

All of your controllers you want to disable caching for then inherit from this controller.

If you need to override the defaults in the NoCacheController class, simply specify the cache settings on your action method and the settings on your Action method will take precedence.

[HttpGet][OutputCache(NoStore = true, Duration = 60, VaryByParam = "*")]public ViewResult Index(){  ...}


HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));HttpContext.Current.Response.Cache.SetValidUntilExpires(false);HttpContext.Current.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);HttpContext.Current.Response.Cache.SetNoStore();

All requests get routed through default.aspx first - so assuming you can just pop in code behind there.