我们的调查表明,并非所有浏览器都以统一的方式尊重HTTP缓存指令。

出于安全原因,我们不希望应用程序中的某些页面被web浏览器缓存。这必须至少适用于以下浏览器:

Internet Explorer 6+Firefox 1.5+Safari 3+歌剧9+铬

我们的要求来自安全测试。从我们的网站注销后,您可以按后退按钮并查看缓存的页面。


当前回答

您可以在IIS中使用位置块来设置单个文件,而不是整个应用程序获取缓存

 <location path="index.html">
    <system.webServer>
      <httpProtocol>
        <customHeaders>
          <add name="Cache-Control" value="no-cache" />
        </customHeaders>
      </httpProtocol>
    </system.webServer>
  </location>

其他回答

在响应中使用pragma标头是一个妻子的故事。RFC2616仅将其定义为请求头

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

头函数的PHP文档有一个相当完整的示例(由第三方提供):

    header('Pragma: public');
    header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");                  // Date in the past   
    header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
    header('Cache-Control: no-store, no-cache, must-revalidate');     // HTTP/1.1
    header('Cache-Control: pre-check=0, post-check=0, max-age=0', false);    // HTTP/1.1
    header ("Pragma: no-cache");
    header("Expires: 0", false);

将修改后的http头设置为1995年的某个日期通常会起作用。

下面是一个示例:

Expires: Wed, 15 Nov 1995 04:58:08 GMT
Last-Modified: Wed, 15 Nov 1995 04:58:08 GMT
Cache-Control: no-cache, must-revalidate

对于ASP.NET Core,创建一个简单的中间件类:

public class NoCacheMiddleware
{
    private readonly RequestDelegate m_next;

    public NoCacheMiddleware( RequestDelegate next )
    {
        m_next = next;
    }

    public async Task Invoke( HttpContext httpContext )
    {
        httpContext.Response.OnStarting( ( state ) =>
        {
            // ref: http://stackoverflow.com/questions/49547/making-sure-a-web-page-is-not-cached-across-all-browsers
            httpContext.Response.Headers.Append( "Cache-Control", "no-cache, no-store, must-revalidate" );
            httpContext.Response.Headers.Append( "Pragma", "no-cache" );
            httpContext.Response.Headers.Append( "Expires", "0" );
            return Task.FromResult( 0 );
        }, null );

        await m_next.Invoke( httpContext );
    }
}

然后在Startup.cs中注册

app.UseMiddleware<NoCacheMiddleware>();

确保在以下位置添加此

app.UseStaticFiles();

我只想指出,如果有人想阻止只缓存动态内容,那么应该以编程方式添加这些额外的头。

我编辑了项目的配置文件,不附加缓存头,但这也禁用了缓存静态内容,这通常是不可取的。修改代码中的响应头可以确保缓存图像和样式文件。

这很明显,但仍值得一提。

还有一个警告。请小心使用HttpResponse类中的ClearHeaders方法。如果你鲁莽地使用它,它可能会给你一些瘀伤。就像它给我的。

重定向ActionFilterAttribute事件后,清除所有标头的后果是丢失所有会话数据和TempData存储中的数据。从Action重定向或在重定向时不清除标头更安全。

再次考虑后,我不鼓励所有人使用ClearHeaders方法。最好单独删除标题。为了正确设置缓存控制头,我使用了以下代码:

filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
filterContext.HttpContext.Response.Cache.AppendCacheExtension("no-store, must-revalidate");