禁用ASP.NET中所有浏览器的浏览器caching

我经历了一个明确的引用,需要ASP.NET代码来禁止浏览器caching页面。 有很多方法来影响HTTP头和元标记,我得到的印象不同的设置是需要不同的浏览器行为正确。 获得参考位代码评论,指出哪些适用于所有浏览器,哪些适用于特定浏览器(包括版本)是非常好的。

关于这个问题有大量的信息,但是我还没有find一个很好的参考来描述每个方法的好处,以及特定的技术是否已经被更高级别的API所取代。

我对ASP.NET 3.5 SP1特别感兴趣,但是也能很好地获得早期版本的答案。

本博客条目Firefox和IEcaching之间的两个重要区别描述了一些HTTP协议的行为差异。

以下示例代码说明了我感兴趣的事物types

public abstract class NoCacheBasePage : System.Web.UI.Page { protected override void OnInit(EventArgs e) { base.OnInit(e); DisableClientCaching(); } private void DisableClientCaching() { // Do any of these result in META tags eg <META HTTP-EQUIV="Expire" CONTENT="-1"> // HTTP Headers or both? // Does this only work for IE? Response.Cache.SetCacheability(HttpCacheability.NoCache); // Is this required for FireFox? Would be good to do this without magic strings. // Won't it overwrite the previous setting Response.Headers.Add("Cache-Control", "no-cache, no-store"); // Why is it necessary to explicitly call SetExpires. Presume it is still better than calling // Response.Headers.Add( directly Response.Cache.SetExpires(DateTime.UtcNow.AddYears(-1)); } } 

这是我们在ASP.NET中使用的:

 // Stop Caching in IE Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); // Stop Caching in Firefox Response.Cache.SetNoStore(); 

它停止Firefox和IE中的caching,但我们还没有尝试其他浏览器。 以下回应标题由这些语句添加:

 Cache-Control: no-cache, no-store Pragma: no-cache 

对于它的价值,我只需要在我的ASP.NET MVC 3应用程序中处理这个。 这是我在Global.asax文件中用于处理所有请求的代码块。

  protected void Application_BeginRequest() { //NOTE: Stopping IE from being a caching whore HttpContext.Current.Response.Cache.SetAllowResponseInBrowserHistory(false); HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache); HttpContext.Current.Response.Cache.SetNoStore(); Response.Cache.SetExpires(DateTime.Now); Response.Cache.SetValidUntilExpires(true); } 

我尝试了各种组合,并让它们在FireFox中失败。 已经有一段时间了,所以上面的答案可以正常工作,否则我可能错过了一些东西。

一直以来,我的工作是将以下内容添加到每个页面的头部或模板(.net中的主页面)。

 <script language="javascript" type="text/javascript"> window.onbeforeunload = function () { // This function does nothing. It won't spawn a confirmation dialog // But it will ensure that the page is not cached by the browser. } </script> 

这已经禁用了所有浏览器中的所有caching。

我知道有两种方法。 首先是告诉浏览器不要caching页面。 将响应设置为不需要caching,但是由于您怀疑浏览器经常忽略此指令。 另一种方法是将您的答复的date时间设置为将来的某个点。 我相信所有的浏览器都会将这个页面添加到caching中来纠正这个问题,但是在进行比较时会显示更新的页面。 我相信可能有些情况下没有做出比较。 我不确定细节,并且随着每个新的浏览器版本的改变。 最后说明我已经有更好的运气,“刷新”自己(另一个响应指令)的页面。 刷新似乎不太可能来自caching。

希望有所帮助。

我要testing在我们的网站上添加“无存储”标签,以查看这对浏览器caching是否有所帮助(Chrome有时会caching页面)。 我还发现这篇文章在caching工作方式和原因的文档上非常有用,如果没有商店是不可靠的,我们将看看ETag的下一篇文章。

http://www.mnot.net/cache_docs/

http://en.wikipedia.org/wiki/HTTP_ETag

另请参见如何防止谷歌浏览器caching我的input,尤其是当用户点击后隐藏的? 否则Chrome可能会重新加载,但保留<input>元素的以前内容 – 换句话说,使用autocomplete="off"