Dynamically cache images in ASP .NET MVC

2.1k views Asked by At

I'm developing some kind of landing page with heavy images. I've cached images on client side using following code in web.config

<staticContent>
  <clientCache httpExpires="Sun, 29 Mar 2020 00:00:00 GMT" cacheControlMode="UseExpires"/>
</staticContent>

Sometimes users, are cropping or re-sizing their images, but browser still shows cached images. Is there any way, I can force tell that image was changed on server, and all browsers should refresh cache.

I guess I need use LastModified HTTP header, but I have no idea how to set this header to static image in ASP .NET MVC

1

There are 1 answers

1
Chris Pratt On BEST ANSWER

The whole point of caching on the client-side is to not check again for a new version for some defined period of time. In this sense, adding a last modified header doesn't help you because the browser won't request the file to get that header. Typically, the method of handling static resources is to set a far future expires, such that the resource will be cached client-side near indefinitely, and then altering the resource name in some way when there's a new version. If the name of the resource changes, then the browser will automatically fetch it again, because it doesn't have a resource with that name.

I'm not sure how your users are doing things, but if you're cropping or resizing images, it's typical to give the image a new name at the same time. For example, the original might be original.jpg, a 200x200 crop might be original_200x200.jpg, etc.

Short of that, you can employ a cache-busting querystring to force the browser to re-request the resource. Simply doing something like appending the last modified date as a timestamp is usually quite effective. For example, instead of referencing the image as image.jpg, you reference it as image.jpg?1416417459. Once the image is modified, the timestamp would be different and would be treated by the browser as an entirely new resource.