在 HTTP 处理程序中,当您知道内容不会更改时返回 304 是否可以接受?
我设置了一个 HTTP 处理程序,它接受 GUID 参数并从文件系统返回图像。
这个形象永远不会改变;如果是,后端程序将生成一个新的 GUID。因此,我希望图像始终被缓存。
从 HTTP 处理程序设置状态代码 304(未修改)是正确的方法吗?
I have an HTTP Handler set up which accepts a GUID parameter and returns the image from the file system.
This image will not ever change; the backend program will generate a new GUID if it does. As such, I want the image to always be cached.
Is the correct way to do this to set a status code of 304 (not modified) from the HTTP Handler?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我建议您设置正确的 HTTP 响应标头,以便向客户端表明内容不会更改并且可以缓存:
I would recommend you setting proper HTTP response headers in order to indicate to the clients that the contents will not change and could be cached:
是的。但是,仅当请求是条件请求时,您才应返回
HTTP/304
。如果您知道该 URL 的图像永远不会更改,则可以设置很长的到期日期(根据规范,最长期限为 1 年)。顺便说一句, RFC 2616 非常容易阅读 - 我建议采取看看那里,了解更多详情。
Yes. However, you should return a
HTTP/304
only if the request is conditional request. If you know the image with that URL never changes, you can set a very long expiry date (1 year is the max according to the specs).BTW, RFC 2616 is quite easy to read -- I suggest to take look there, for further details.
另外,除了 @Darin 的回复之外,您还遇到过 ETag 吗?这些是像您建议的那样实现缓存的常见方法之一。浏览器第一次请求图像时,您不会有 ETag,因此您知道要提供图像。下次发出请求时,它将提供 ETag - 然后您可以使用它来查看是返回 304 还是图像本身。在您的示例中,您只会检查 ETag 是否存在。
对于您提出的解决方案,我关心的是如何从后续请求(以及来自多个客户端)中识别第一个请求
Also in addition to @Darin's response, have you come across ETags? These are one of the common way of implementing caching like you propose. The first time the browser requests the image you won't have an ETag so you know to serve up the image. The next time a request is made it will provide the ETag - which you can then use to see whether to return a 304 or the image itself. In your example you would only be checking for the presence of an ETag or not.
With your proposed solution what would concern me is how do you identify the first request from subsequent requests (and from more than one client)