Forcing Retrieval of Images in ASP.NET/MVC

Posted: June 3rd, 2015 | Author: | Filed under: .Net, ASP.NET MVC, Web | No Comments »

Browsers cache images in order to speed up page load times. If an action on a controller generates dynamic images, this can be a problem, since the user will only see the first image fetched by the browser. One way to force the browser to by-pass its cache and actually retrieve the image is to append a random parameter to the URL for the action.
For example: A user uploads an image to the server and the server subsequently returns some HTML showing the image. The user then performs an action which triggers the server to alter the image in some way (for example cropping or resizing), and returns the HTML once again. However, the browser sees that the link to the image is the same, and therefore it simply shows the initial image which it has already cached.

So, instead of generating the image URL with razor syntax like this:

<img src=”@Url.Action(“GetPhoto”)” />

Simply add some random parameter (or just anything the browser has not seen before) to force it to download the image again:

<img src=”@Url.Action(“GetPhoto”, new {ticks = DateTime.UtcNow.Ticks})” />