[asp.net] Disabling browser caching for all browsers from ASP.NET

I'm after a definitive reference to what ASP.NET code is required to disabled browsers from caching the page. There are many ways to affect the HTTP headers and meta tags and I get the impression different settings are required to get different browsers to behave correctly. It would be really great to get a reference bit of code commented to indicate which works for all browsers and which is required for particular browser, including versions.

There is a huge amount of information about this issue there but I have yet to find a good reference that describes the benefits of each method and whether a particular technique has been superseded by a higher level API.

I'm particularly interested in ASP.NET 3.5 SP1 but it would be good to get answers for earlier version as well.

This blog entry Two Important Differences between Firefox and IE Caching describes some HTTP protocol behaviour differences.

The following sample code illustrates the kind of thing I am interested in

public abstract class NoCacheBasePage : System.Web.UI.Page
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        DisableClientCaching();
    }

    private void DisableClientCaching()
    {
        // Do any of these result in META tags e.g. <META HTTP-EQUIV="Expire" CONTENT="-1">
        // HTTP Headers or both?

        // Does this only work for IE?
        Response.Cache.SetCacheability(HttpCacheability.NoCache);

        // Is this required for FireFox? Would be good to do this without magic strings.
        // Won't it overwrite the previous setting
        Response.Headers.Add("Cache-Control", "no-cache, no-store");

        // Why is it necessary to explicitly call SetExpires. Presume it is still better than calling
        // Response.Headers.Add( directly
        Response.Cache.SetExpires(DateTime.UtcNow.AddYears(-1));
    }
}

This question is related to asp.net http browser caching

The answer is


I've tried various combinations and had them fail in FireFox. It has been a while so the answer above may work fine or I may have missed something.

What has always worked for me is to add the following to the head of each page, or the template (Master Page in .net).

<script language="javascript" type="text/javascript">
    window.onbeforeunload = function () {   
        // This function does nothing.  It won't spawn a confirmation dialog   
        // But it will ensure that the page is not cached by the browser.
    }  
</script>

This has disabled all caching in all browsers for me without fail.


See also How to prevent google chrome from caching my inputs, esp hidden ones when user click back? without which Chrome might reload but preserve the previous content of <input> elements -- in other words, use autocomplete="off".


For what it's worth, I just had to handle this in my ASP.NET MVC 3 application. Here is the code block I used in the Global.asax file to handle this for all requests.

    protected void Application_BeginRequest()
    {
        //NOTE: Stopping IE from being a caching whore
        HttpContext.Current.Response.Cache.SetAllowResponseInBrowserHistory(false);
        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        HttpContext.Current.Response.Cache.SetNoStore();
        Response.Cache.SetExpires(DateTime.Now);
        Response.Cache.SetValidUntilExpires(true);
    }

There are two approaches that I know of. The first is to tell the browser not to cache the page. Setting the Response to no cache takes care of that, however as you suspect the browser will often ignore this directive. The other approach is to set the date time of your response to a point in the future. I believe all browsers will correct this to the current time when they add the page to the cache, but it will show the page as newer when the comparison is made. I believe there may be some cases where a comparison is not made. I am not sure of the details and they change with each new browser release. Final note I have had better luck with pages that "refresh" themselves (another response directive). The refresh seems less likely to come from the cache.

Hope that helps.


I'm going to test adding the no-store tag to our site to see if this makes a difference to browser caching (Chrome has sometimes been caching the pages). I also found this article very useful on documentation on how and why caching works and will look at ETag's next if the no-store is not reliable:

http://www.mnot.net/cache_docs/

http://en.wikipedia.org/wiki/HTTP_ETag


Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to http

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Axios Delete request with body and headers? Read response headers from API response - Angular 5 + TypeScript Android 8: Cleartext HTTP traffic not permitted Angular 4 HttpClient Query Parameters Load json from local file with http.get() in angular 2 Angular 2: How to access an HTTP response body? What is HTTP "Host" header? Golang read request body Angular 2 - Checking for server errors from subscribe

Examples related to browser

How to force reloading a page when using browser back button? How do we download a blob url video How to prevent a browser from storing passwords How to Identify Microsoft Edge browser via CSS? Edit and replay XHR chrome/firefox etc? Communication between tabs or windows How do I render a Word document (.doc, .docx) in the browser using JavaScript? "Proxy server connection failed" in google chrome Chrome - ERR_CACHE_MISS How to check View Source in Mobile Browsers (Both Android && Feature Phone)

Examples related to caching

Disable nginx cache for JavaScript files How to prevent Browser cache on Angular 2 site? Curl command without using cache Notepad++ cached files location Laravel 5 Clear Views Cache Write-back vs Write-Through caching? Tomcat 8 throwing - org.apache.catalina.webresources.Cache.getResource Unable to add the resource Chrome - ERR_CACHE_MISS How do I use disk caching in Picasso? How to clear gradle cache?