【发布时间】:2011-10-10 04:26:19
【问题描述】:
我发出了一个 Ajax 请求,在其中设置了响应可缓存性和最后修改的标头:
if (!String.IsNullOrEmpty(HttpContext.Current.Request.Headers["If-Modified-Since"]))
{
HttpContext.Current.Response.StatusCode = 304;
HttpContext.Current.Response.StatusDescription = "Not Modified";
return null;
}
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.Public);
HttpContext.Current.Response.Cache.SetLastModified(DateTime.UtcNow);
这按预期工作。第一次发出 Ajax 请求时,我得到了200 OK。我第二次收到304 Not Modified。
当我在 Chrome 中硬刷新 (Ctrl+F5) 时,我得到 200 OK - 太棒了!
当我在 Internet Explorer/Firefox 中硬刷新时,我得到304 Not Modified。但是,所有其他资源 (JS/CSS/HTML/PNG) 都会返回 200 OK。
原因是“If-Not-Modified”标头是为 XMLHttpRequest 发送的,无论这些浏览器中的硬刷新如何。我相信 Steve Souders 记录了它 here。
我尝试设置一个 ETag 并在“If-None-Match”上进行调节,但无济于事(Steve Souders 页面的 cmets 中提到了这一点)。
这里有没有人得到任何智慧的宝石?
谢谢, 本
更新
我可以对照存储的最后修改日期检查“If-Modified-Since”。但是,希望这个问题能帮助其他发现标头设置错误的 SO 用户。
更新 2
虽然每次发送请求时都带有“If-Modified-Since”标头。如果到期未设置或设置为未来日期,Internet Explorer 甚至不会发出请求。没用!
更新 3
这还不如现在是一个实时博客。 Internet Explorer 不会在 localhost 时发出第二个请求。使用真实 IP 或环回将起作用。
【问题讨论】:
-
您是否尝试通过在脚本 src 路径中使用随机数或日期时间值更改每个请求的文件名来防止缓存(如 src='myscript.js?q=45920')?跨度>
-
我希望它被缓存,除非它来自硬刷新。因此设置随机查询字符串参数没有帮助。不过感谢您的建议!
标签: javascript asp.net internet-explorer caching xmlhttprequest