在MVC 3中禁用部分视图的缓存

本文关键字:视图 缓存 用部 MVC | 更新日期: 2023-09-27 18:19:44

我有一个部分视图在不应该缓存的时候被缓存的问题。这个部分视图用于在页面上显示登录/注销。它使用下面的简单代码来确定显示的链接

@if(Request.IsAuthenticated) {    
    <a href="@Url.Action("LogOff", "Account", new { area = "" })">Log Off</a> 
}
else {
    <a href="@Url.Action("LogOn", "Account", new { area = "" })">Log On</a>
}

这个部分视图是从MVC3应用程序中的所有页面调用的,使用

@Html.Partial("_HeaderView")  

在我的大多数控制器中,我都定义了输出缓存,所以我可以利用缓存内容的优势。

[OutputCache(Duration = 86400, VaryByParam = "*")]

现在我的问题是,当我不希望部分视图被缓存时,整个页面都被缓存了。这导致了错误的行为,即使用户没有登录,它有时也会显示LogOff。有没有办法缓存所有内容,除了有问题的部分视图?

在MVC 3中禁用部分视图的缓存

您可以通过用以下内容装饰显示_HeaderView部分的控制器来禁用缓存:

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult HeaderView()
{
    return PartialView("_HeaderView");
}

您正在寻找的是所谓的甜甜圈缓存。这是一篇很好的文章,解释了它是什么以及如何使它发挥作用http://www.devtrends.co.uk/blog/donut-output-caching-in-asp.net-mvc-3

我们应该在Web.config文件中设置缓存配置文件,而不是在页面中单独设置缓存值,以避免冗余代码。我们可以使用OutputCache属性的CacheProfile属性来引用配置文件。此缓存配置文件将应用于所有页面,除非页面/方法覆盖这些设置。

<system.web>
  <caching>
    <outputCacheSettings>
      <outputCacheProfiles>
        <add name="CacheProfile" duration="60" varyByParam="*" />
      </outputCacheProfiles>
    </outputCacheSettings>
  </caching>
</system.web>

如果你想从返回部分视图[_HeaderView]的操作中禁用缓存,你可以通过装饰特定的操作方法来覆盖配置缓存设置,如下所示:

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult RenderPartialView()
{
    return PartialView("_HeaderView");
}

希望这对你有帮助!

这对我有效..

 public ActionResult LogOff()
 {
     AuthenticationManager.SignOut();  
     var url = Url.Action("Index", "Web"); 
     HttpResponse.RemoveOutputCacheItem(url);           
     return RedirectToAction("Index", "Web");
 }

回到MVC后,花了一点时间才弄清楚这一点。只需将"缓存"设置直接放在"部分标头视图"中即可。如在显示用户名时所示。不需要全局或服务器端代码。唯一的问题是,一旦页面被缓存,它将不会在登录后立即刷新。但在最初浏览产品时,我们会在需要时保持速度。好吧,在我们的情况下进行权衡。

@if(Request.IsAuthenticated){@*当我们通过身份验证时,不要再缓存了*@HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);HttpContext.Current.Response.Cache.SetNoStore();HttpContext.Current.Response.Cache.SetNoServerCaching();@*@Html.Raw(DateTime.Now.ToString())*@@Html.ActionLink("Welcome"+(String.IsNullOrEmpty(((System.Security.Cclams.IclamsIdentity)User.Identity).FindFirstValue("UserName"))?User.Identity.Name:((System.Security.ClaimsIdentity)User.Identity).FindFirstValue}其他的{}

快进到2023年,在.NET Core中,您可以执行以下操作来关闭页面某些部分的缓存:

<cache enabled="false">
@if(Request.IsAuthenticated) {    
    <a href="@Url.Action("LogOff", "Account", new { area = "" })">Log Off</a> 
}
else {
    <a href="@Url.Action("LogOn", "Account", new { area = "" })">Log On</a>
}
</cache>

在此处阅读有关<cache>标记帮助程序的更多信息:https://learn.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/built-in/cache-tag-helper?view=aspnetcore-7.0