Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileContentResult - prevent browser caching image

I'm returning an image (png) from a call to an action method and I'd like to stop the image being cached by the browser.

return File(reply, "image/png", "{0}_Graph".FormatWith(ciName));

I've tried all the usual things, appending an array of different headers to the file output response and none of them seem to be working for me.

Basically my action method returns a graph that's generated on the server and could be different from moment to moment. I use Javascripts Image object on the client side and set its src to my action method.

var image = new Image();
image.src = baseUrl + params;

Each time the same URL is requested, the server is not hit.

I can append a random number etc to the querystring however I'm wondering if there's a better approach.

like image 283
Jamie Dixon Avatar asked Jun 08 '26 22:06

Jamie Dixon


1 Answers

You can set appropriate HTTP headers to prevent caching (I do not know how to do this in ASP.NET, but I imagine it would be something like HTTP.Response.setHeader("foo", "bar"):

"Pragma-directive: no-cache"
"Cache-directive: no-cache"
"Cache-control: no-cache"
"Pragma: no-cache"
"Expires: 0"

or use the current timestamp if you don't like the random number solution:

image.src = baseUrl + params + '&t=' + new Date().getTime();
like image 70
karim79 Avatar answered Jun 10 '26 10:06

karim79



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!