Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IIS 7 Force Fresh Images

How do I force IIS 7 to not cache images for a particular page?

like image 387
Esteban Araya Avatar asked Dec 18 '09 22:12

Esteban Araya


People also ask

Does IIS cache images?

IIS automatically caches static content (such as HTML pages, images, and style sheets), since these types of content do not change from request to request. IIS also detects changes to the files when you make updates, and IIS flushes the cache as needed.

What is Max age in cache control?

Cache-control: max-age It is the maximum amount of time specified in the number of seconds. For example, max-age=90 means that a HTTP response remains in the browser as a cached copy for the next 90 seconds before it can be available for reuse.


2 Answers

I would have thought that it is your browser doing the caching.

In any case one way around this as long as your link is not statically declared in the html, is to append a random number on the end of the images url:

<img src="http://mywebsite/images/mypic.png?a=123456" />

the argument means nothing because you are doing nothing with it, but to the browser it looks like a new uncached link.

How you put that random number on the end is up to you:

<img src="javascript:getMyLink();" />

or from the code behind:

Image myImage = new Image();
myImage.Source = "myurl?a=" + Guid.NewGuid().ToString();
someOtherControl.Controls.Add(myImage);

(of course this is pseudo code, you need to check that the property names are correct).

like image 144
slugster Avatar answered Oct 16 '22 20:10

slugster


In IIS7, you can do this either declaratively in your web.config, or programmatically.

<location path="YourPath">
  <system.webServer>
    <staticContent>
      <clientCache cacheControlMode="DisableCache" />
    </staticContent>
  </system.webServer>
</location>

The programmatic solution requires a simple HttpModule that's registered to run for all requests in Integrated mode, where you look for the URLs that you're concerned about. Then call:

context.Response.Cache.SetCacheability(HttpCacheability.NoCache);

FWIW, you may want to consider disabling client-side caching only, while enabling server-side caching, by using HttpCacheability.ServerAndNoCache. Also, if you add a query string on the image names, you will prevent server-side caching by http.sys.

In case it helps, I cover techniques like these in detail in my book: Ultra-Fast ASP.NET.

like image 20
RickNZ Avatar answered Oct 16 '22 19:10

RickNZ