从ASP.NET禁用所有浏览器的浏览器缓存

Mar*_*rth 84 browser asp.net caching http

我正在明确提到禁用浏览器缓存页面所需的ASP.NET代码.有很多方法可以影响HTTP标头和元标记,我得到的印象是需要不同的设置才能使不同的浏览器正常运行.获得一个评论的参考位以表明哪些适用于所有浏览器以及哪些适用于特定浏览器(包括版本)是非常好的.

关于这个问题有大量的信息,但我还没有找到一个很好的参考资料来描述每种方法的好处,以及某种技术是否已被更高级别的API取代.

我对ASP.NET 3.5 SP1特别感兴趣,但同样可以获得早期版本的答案.

此博客文章Firefox和IE缓存之间的两个重要差异描述了一些HTTP协议行为差异.

以下示例代码说明了我感兴趣的内容

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 e.g. <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));
    }
}
Run Code Online (Sandbox Code Playgroud)

Htt*_*ort 96

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

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

// Stop Caching in Firefox
Response.Cache.SetNoStore();
Run Code Online (Sandbox Code Playgroud)

它在Firefox和IE中停止缓存,但我们还没有尝试过其他浏览器.这些语句添加了以下响应头:

Cache-Control: no-cache, no-store
Pragma: no-cache
Run Code Online (Sandbox Code Playgroud)

  • 显然有人发现使用SetCacheability和NoCache也会禁用ASP.NET输出缓存(服务器端缓存).他们建议使用ServerAndNoCache选项.http://codeclimber.net.nz/archive/2007/04/01/Beware-the-ASP.NET-SetCacheability-method.aspx (12认同)
  • +1这对我在Chrome中很有用,非常感谢.我也使用Response.Cache.SetAllowResponseInBrowserHistory(true); 避免历史记录为同一页面的每个请求存储条目. (5认同)
  • FWIW ...需要为IE10添加SetNoStore (3认同)

Ada*_*arr 39

对于它的价值,我只需要在我的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);
    }
Run Code Online (Sandbox Code Playgroud)

  • @Evan,Application_BeginRequest只会被调用从IIS发送到ASP.NET的请求.很多时候,像CSS,JS,图像,字体等静态文件是从IIS中被视为静态文件而不被发送到ASP.NET运行时的扩展.如果IIS设置为将所有请求发送到ASP.NET运行时,则是​​,这将适用于所有请求,即使文件是静态的并且应该被缓存. (5认同)
  • -1,在这些Application_BeginRequest()中设置会导致为您可能希望缓存的项目(JavaScript文件,图像等)发送无缓存标头.我还没有尝试过,但OP的位置(在ASP页面中设置标题)可能更好. (2认同)