我有一个自定义处理程序,可以将图像返回给浏览器。
图像是从数据库中获取的。
由于某些原因,浏览器没有缓存图像,我想知道是否有人能够从下面的代码中发现我遗漏的内容:
HttpContext.Current.Response.BinaryWrite(imageBytes);
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.Public);
Context.Current.Response.Cache.SetAllowResponseInBrowserHistory(true);
if(imgRepGetCache.DateCached.HasValue)
HttpContext.Current.Response.Cache.SetLastModified(imgRepGetCache.DateCached.Value);
HttpContext.Current.Response.Cache.SetExpires(DateTime.Now.AddDays(2));
HttpContext.Current.Response.ContentType = "image/jpeg";
或者如果我以某种方式完全忽略了要点并且还有其他地方我需要查看。
编辑:根据请求获取更多信息:
- URL 始终相同
- 我正在测试通过标准 IIS 管道和我的管道在同一台 PC 的同一浏览器中加载同一文件。通常通过 IIS 加载的文件被缓存,我的文件没有。
编辑 2: 在检查正常 IIS 路由上的 HTTP 请求/响应后,我认为它与 ETag 有关。 ETag(我现在还不熟悉)似乎是文档的一种校验和。在浏览器的后续请求中,将发送 ETag,如果服务器发现 ETag 未更改,则返回 304 - Not Modified。都好!但我现在使用以下方法设置 ETag:
HttpContext.Current.Response.Cache.SetETag(imgRepGetCache.DateCached.ToString());
但它没有出现在响应中。更近...
编辑 3: 在利用 Firebug 获得一些 HTTP 检查乐趣后,我最终修复了它。我在下面发布了我的解决方案。
最佳答案
好的,我修好了。
以下是我为其他人所做的以及我自己 future 的引用:
// Check for repeated request for the same image from a browser
if (HttpContext.Current.Request.Headers.Get("If-None-Match") == imgRepGetCache.DateCached.Value.ToString())
{
// Return 304 - Not Modified
HttpContext.Current.Response.Status = "304 Not Modified";
}
else
{
if (imgRepGetCache.DateCached.HasValue)
HttpContext.Current.Response.Headers.Set("Etag", imgRepGetCache.DateCached.Value.ToString());
// ... do my other stuff here
}
很有魅力!
如果有人在这里发现任何潜在问题,请告诉我,以便我进行更新。
为了先发制人 - 我可以 100% 依赖日期字符串来识别图像是否是新的(在我的特定情况下)。
关于image - 为什么我的自定义交付图像没有缓存在浏览器中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/963123/