Clear all image in browser cache

Viewed 656

I have an ASP.NET C# application that contains images. I went in and modified some of my images that are used in the application but didn't change the name. I know that if I change the name, it will download the new image to the browser, but if my clients have already visited that page, that image will most likely be cached on the client machine.

I was wondering, is there a way through the GLOBAL.ASAX page in the session start, to indicate that the website should pull all information and download and disregard all local cached data?

This would be helpful as well for JS and CSS files. Right now I append a URL parameter based on the version of the application... I would hate to do that for all images...

1 Answers

You can use the Clear-Site-Data HTTP header.

The Clear-Site-Data header clears browsing data (cookies, storage, cache) associated with the requesting website. It allows web developers to have more control over the data stored locally by a browser for their origins.

It is still mark as experimental but should work in all modern browsers. See Clear-Site-Data from the MDN documentation for more information.

You can set this header like this :

response.Headers.Add("Clear-Site-Data", "cache");

If you want to refresh the cache each time a new version is published, you can combine this with a cookie and use this code in your global.asax :

protected void Application_BeginRequest(object sender, EventArgs e)
{
    var request = ((HttpApplication)sender).Request;
    var response = ((HttpApplication)sender).Response;

    var versionCookie = request.Cookies["version"];

    if (versionCookie == null)
    {
        versionCookie = new HttpCookie("version");
        versionCookie.Expires = DateTime.Now.AddYears(5);
    }

    if (versionCookie.Value != currentVersion)
    {
        versionCookie.Value = currentVersion;
        response.SetCookie(versionCookie);
        response.Headers.Add("Clear-Site-Data", "cache");
    }
}
Related