【问题标题】:How to clear browser cache on browser back button click in MVC4?如何在 MVC4 中单击浏览器后退按钮时清除浏览器缓存?
【发布时间】:2013-05-02 11:40:06
【问题描述】:

我知道这是 stackoverflow 中的一个热门问题。我经历了每一个相同的问题,但我无法为我找到正确的答案。 这是我的注销控制器操作结果

    [Authorize]       
    public ActionResult LogOut(User filterContext)
    {
        Session.Clear();
        Session.Abandon();
        Session.RemoveAll();
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
        Response.Cache.SetNoStore();
        FormsAuthentication.SignOut();
        return RedirectToAction("Home", true);

    }

它对我不起作用。 我也尝试添加 -

<meta http-equiv="Cache-Control" content="no-cache" /> <meta http-equiv="Pragma" content="no-cache"/> <meta http-equiv="Expires" content="0"/>

这些都没有解决我的问题。

【问题讨论】:

  • 回到哪里?任何地方?还是只是一个特定的动作?

标签: c# asp.net-mvc asp.net-mvc-4 browser-cache


【解决方案1】:

您的方法的问题在于您将其设置在 MVC 应用它已经太晚的地方。应将以下三行代码放在显示您不想显示的视图(因此是页面)的方法中。

Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
Response.Cache.SetNoStore();

如果您想在所有页面上应用“浏览器背面不缓存”行为,那么您应该将它放在 global.asax 中。

protected void Application_BeginRequest()
{
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
    Response.Cache.SetNoStore();
}

【讨论】:

  • 为什么没有被接受,为什么没有得到更多的支持?经过数小时的谷歌搜索,这是唯一适用于所有浏览器的解决方案。
  • 先生,您是我今天的英雄。
  • 这将影响 MVC 应用程序中 bundle 的概念,js & css 文件不会被缓存,并且每次重新加载或返回 js & css 文件都会从服务器而不是浏览器缓存再次加载
【解决方案2】:

只需在操作上设置输出缓存。我在很多项目中都使用过这种方法:

[HttpGet, OutputCache(NoStore = true, Duration = 1)]
public ActionResult Welcome()
{
    return View();
}

如果用户向后/向前导航到您的视图,上述属性将基本上指示浏览器从您的控制器操作中获取页面的新副本。

您还可以在 web.config 中定义您的缓存并与此属性结合使用以避免一些重复。见here

【讨论】:

  • 这对我很有帮助。如果您想缓存静态文件/图像等但不想缓存页面(视图),此解决方案最适合这种情况。
猜你喜欢
  • 2015-10-22
  • 1970-01-01
  • 2019-11-30
  • 2011-10-15
  • 1970-01-01
  • 1970-01-01
  • 2013-03-02
  • 1970-01-01
  • 2012-05-17
相关资源
最近更新 更多