javascript - Internet Explorer/Firefox 中的硬刷新和 XMLHttpRequest 缓存

标签 javascript asp.net internet-explorer caching xmlhttprequest

我发出一个 Ajax 请求,在其中设置响应缓存能力和最后修改的 header :

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” header 是为 XMLHttpRequest 发送的,而不管这些浏览器中的硬刷新如何。我相信 Steve Souders 记录了它 here .

我已经尝试设置一个 ETag 并在“If-None-Match”上进行调节,但无济于事(Steve Souders 页面的评论中提到了这一点)。

有没有人在这里得到任何智慧的 gem ?

谢谢, 本

更新

我可以根据存储的上次修改日期检查“If-Modified-Since”。但是,希望这个问题能帮助其他发现 header 设置不正确的 SO 用户。

更新 2

每次发送请求时都带有“If-Modified-Since” header 。如果未设置过期时间或设置为 future 日期,Internet Explorer 甚至不会发出请求。没用!

更新 3

现在这也可能是一个实时博客。当 localhost 时,Internet Explorer 不会费心发出第二个请求。使用真实 IP 或环回即可。

最佳答案

在 IE10 之前,IE 不会将刷新标志(请参阅 http://blogs.msdn.com/b/ieinternals/archive/2010/07/08/technical-information-about-conditional-http-requests-and-the-refresh-button.aspx)应用于不是作为文档加载的一部分发出的请求。

如果需要,您可以调整目标 URL 以包含随机数,以防止缓存的副本满足 future 的请求。或者,您可以发送 max-age=0 以强制 IE 在每次重用之前有条件地重新验证资源。

至于为什么浏览器会重用一个没有指定生命周期的缓存资源,请看http://blogs.msdn.com/b/ie/archive/2010/07/14/caching-improvements-in-internet-explorer-9.aspx

关于javascript - Internet Explorer/Firefox 中的硬刷新和 XMLHttpRequest 缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6775759/

相关文章:

c# - 动态设置 web.config 中的值?

c# - 从 php 平滑过渡到 asp.net c#

javascript - Internet Explorer 在 getElementById 上抛出错误

html - 是否可以阻止从我的站点保存图像?

javascript - 将数字转换为字母字符串 (Javascript)

javascript - 使用 jquery(简单的文本编辑器)向 textarea 添加值

javascript - 完整日历无法识别 Chrome 中日期字段上的点击事件?

html - 水平菜单 - IE 中的空白

多维条形图的Javascript可视化包

javascript - 收听页面内容已更新