简体   繁体   English

FileContentResult - 阻止浏览器缓存图像

[英]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. 我正在从调用动作方法返回一个图像(png),我想停止浏览器缓存图像。

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. 我在客户端使用Javascripts Image对象并将其src设置为我的action方法。

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

Each time the same URL is requested, the server is not hit. 每次请求相同的URL时,服务器都不会被命中。

I can append a random number etc to the querystring however I'm wondering if there's a better approach. 我可以在查询字符串中附加一个随机数等,但我想知道是否有更好的方法。

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") : 您可以设置适当的HTTP标头以防止缓存(我不知道如何在ASP.NET中执行此操作,但我想它会像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();

Since this is MVC, use the MVC OutputCache attribute. 由于这是MVC,因此请使用MVC OutputCache属性。 See my response at: Disable browser cache for entire ASP.NET website 请参阅我的回复: 禁用整个ASP.NET网站的浏览器缓存

Also remember to clear your cache before trying this. 还记得在尝试之前清除缓存。 If it's already caches then results can be inconsistent. 如果它已经缓存,则结果可能不一致。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM