【问题标题】:MVC3 custom outputcacheMVC3 自定义输出缓存
【发布时间】:2011-04-08 03:44:03
【问题描述】:

我想在我的应用程序中使用缓存,但我返回的数据是特定于登录用户的。当我需要因用户而异时,我不能使用任何开箱即用的缓存规则。

有人能指出我创建自定义缓存属性的正确方向吗?从控制器中,我可以从Thread.CurrentPrincipal.Identity; 或我在控制器构造函数_user 中初始化的私有控制器成员访问用户

谢谢。

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-2 asp.net-mvc-3


    【解决方案1】:

    您可以使用 VaryByCustom。在 Global.asax 中覆盖 GetVaryByCustomString 方法:

    public override string GetVaryByCustomString(HttpContext context, string arg)
    {
        if (arg == "IsLoggedIn")
        {
             if (context.Request.Cookies["anon"] != null)
             {
                  if (context.Request.Cookies["anon"].Value == "false")
                  {
                       return "auth";
                  }
                  else
                  {
                       return "anon";
                  }
              }
              else
              {
                 return "anon";
              }
        }
        else
        {
            return base.GetVaryByCustomString(context, arg);
        }
    }
    

    然后使用 OutputCache 属性:

    [OutputCache(CacheProfile = "MyProfile")]
    public ActionResult Index()
    {
       return View();
    }
    

    在 web.config 中:

    <caching> 
        <outputcachesettings>             
            <outputcacheprofiles> 
                <clear /> 
                <add varybycustom="IsLoggedIn" varybyparam="*" duration="86400" name="MyProfile" /> 
            </outputcacheprofiles> 
        </outputcachesettings> 
    </caching>
    

    【讨论】:

    【解决方案2】:

    Authorize 属性在缓存授权用户和未授权用户方面发生了一些有趣的事情。您可以提取它的逻辑并将其修改为缓存每个授权用户,而不仅仅是“用户被授权”。

    看看这篇文章:

    Can someone explain this block of ASP.NET MVC code to me, please?

    【讨论】:

      【解决方案3】:

      您应该使用OutputCache.VaryByCustom Property 来指定自定义变化字符串。要使用它,您应该覆盖 Global.asax 中的方法

      public override string GetVaryByCustomString(HttpContext context, string arg) 
      { 
        if(arg.ToLower() == "currentuser") 
        { 
          //return UserName;
        } 
        return base.GetVaryByCustomString(context, arg); 
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-06-25
        • 1970-01-01
        • 1970-01-01
        • 2011-08-13
        • 2012-12-08
        • 2011-04-13
        • 2015-03-22
        • 2013-02-09
        相关资源
        最近更新 更多