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

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

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

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


当前回答

对于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();

其他回答

此外,如果您使用.htaccess文件启用缓存,请确保重置该文件中的ExpiresDefault。

ExpiresDefault "access plus 0 seconds"

然后,可以使用ExpiresByType为要缓存的文件设置特定值:

ExpiresByType image/x-icon "access plus 3 month"

如果您的动态文件(如php等)被浏览器缓存,并且您无法找出原因,那么这可能也很有用。选中ExpiresDefault。

除了标题之外,还可以考虑通过https为页面提供服务。许多浏览器默认不会缓存https。

我用这种方式解决了。

2个注意事项:

1) 服务器端事件不是在后退单击时触发的,而是javascript。

2) 我有两个javascript来读/写cookie

function setCookie(name, value, days)
{
    var expires = "";
    if (days)
    {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "") + expires + "; path=/";
}

function getCookie(name)
{
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');

    for (var i = ca.length - 1; i >= 0; i--)
    {
        var c = ca[i];
        while (c.charAt(0) == ' ')
        {
            c = c.substring(1, c.length);
        }

        if (c.indexOf(nameEQ) == 0)
        {
            return c.substring(nameEQ.length, c.length);
        }
    }
    return null;
}

在我的Page_Load中,我插入了以下内容:(这不是在单击后启动的)

    protected void Page_Load(object sender, EventArgs e)
    {
       Page.RegisterClientScriptBlock("", "<script>setCookie('" + Session.SessionID + "', '" + Login + "', '100');</script>");
    }

其中“Login”是我的id值,注销后为-1(可以使用其他值,例如布尔值)。

然后在我的页面中添加了以下内容:(这是在单击后启动的)

<script type="text/javascript">
if (getCookie('<%= Session.SessionID %>') < 0)
        {
            if (history.length > 0)
            {
                history.go(+1);
            }
        }

</script>

没有别的。

使用此解决方案,仅在同一浏览器上的每个页面注销后,才在每个页面上启用反向单击。

通过设置Pragma:无缓存

IE6中存在错误

即使使用“缓存控制:无缓存”,也始终缓存具有“内容编码:gzip”的内容。

http://support.microsoft.com/kb/321722

您可以为IE6用户禁用gzip压缩(检查用户代理中的“MSIE6”)