【问题标题】:Why GetVaryByCustomString is not called为什么不调用 GetVaryByCustomString
【发布时间】:2012-10-17 09:47:49
【问题描述】:

使用下面的代码在 ASP.NET MVC2 中实现输出缓存。

GetVaryByCustomString 方法未调用:将断点置于其第一行并运行应用程序显示未到达断点。 到达控制器 Index() 中的断点。

如何在ASP.NET MVC2中使用VaryByCustom?

控制器:

        [OutputCache(VaryByCustom = "user")]
        public ActionResult Index(string _entity, string id)
        {
...

Global.asax.cs:

public class MvcApplication : System.Web.HttpApplication
{
    public  override string GetVaryByCustomString(HttpContext context, string arg)
    {
        if (arg == "user")
        {
            HttpCookie cookie = context.Request.Cookies["Company"];
            if (cookie != null)
                return Thread.CurrentPrincipal.Identity.Name + "," + cookie.Value;
            return Thread.CurrentPrincipal.Identity.Name;
        }
        return base.GetVaryByCustomString(context, arg);
    }

}

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-2 outputcache


    【解决方案1】:

    您的 OutputCache 定义错误。您必须指定Duration:

    [OutputCache(VaryByCustom = "user", Duration = 50)]
    public ActionResult Index(string _entity, string id)
    

    现在将调用您覆盖的 GetVaryByCustomString 方法。另外别忘了GetVaryByCustomString 方法只有在控制器动作执行完毕后才会被调用。

    【讨论】:

    • 谢谢。添加此 Vary:* 标头后,将发送到浏览器,这将禁用浏览器缓存。如何使用 VaryByCustom 启用浏览器缓存?
    【解决方案2】:

    我只想提两个其他原因

    如果项目中有任何 [NoCache] 属性,GetVaryByCustomString 将不会触发。

    如果你放

    Location = OutputCacheLocation.Client, 
    

    GetVaryByCustomString 不会触发。

    【讨论】:

      【解决方案3】:

      我最近参与的一个项目有一个全局过滤器阻止输出缓存工作:

      public class FilterConfig
      {
          public static void RegisterGlobalFilters(GlobalFilterCollection filters)
          {
              filters.Add(new NoCacheResponseAttribute());
          }
      }
      
      public class NoCacheResponseAttribute : BaseActionFilterAttribute
      {
          public override void OnActionExecuted(ActionExecutedContext filterContext)
          {
             var response = filterContext.RequestContext.HttpContext.Response;
             response.Cache.SetCacheability(HttpCacheability.NoCache);
             response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
             response.Cache.SetNoStore();
          }
      }
      

      注释添加过滤器的行后,输出缓存开始按预期工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-15
        • 2020-03-28
        • 2019-03-18
        • 2011-05-04
        • 2019-11-04
        • 2016-10-27
        • 2018-05-24
        • 2013-08-12
        相关资源
        最近更新 更多