3

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.

Jamie Dixon
  • 49,653
  • 18
  • 119
  • 157

2 Answers2

1

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();
karim79
  • 326,960
  • 63
  • 404
  • 402
  • `It should be image.src = baseUrl + params + "&ts=" + new Date().getTime();` If the & is left off the time value would append to the last value in the querystring. – epascarello Aug 31 '11 at 13:26
1

Since this is MVC, use the MVC OutputCache attribute. See my response at: Disable browser cache for entire ASP.NET website

Also remember to clear your cache before trying this. If it's already caches then results can be inconsistent.

Community
  • 1
  • 1
Adam Tuliper - MSFT
  • 29,569
  • 4
  • 49
  • 68
  • Thanks Adam. I'm using the OutputCache attribute as you've sugested however calls to the same action method in the image src are still not hitting the server. The first one hits the server fine it's just any request after the first one. – Jamie Dixon Aug 31 '11 at 13:53
  • how is your browser setup? Which browser? IE? Are you set to get new files on every request or "Automatically". IE is finicky at times. Load up the fool fiddler and see if the request is even coming out. If it isn't - then its IE (or whatever browser). Also examine the no-cache headers that should be sent in the request. What version browser are you using? – Adam Tuliper - MSFT Aug 31 '11 at 15:24
  • I'm testing in FF6. I'll check the things you've mentioned. – Jamie Dixon Aug 31 '11 at 15:26