MVC3自定义输出缓存

BZi*_*ink 5 asp.net-mvc asp.net-mvc-3 asp.net-mvc-2

我想在我的应用程序中使用缓存,但我返回的数据特定于登录用户.当我需要因用户而异时,我无法使用任何现成的缓存规则.

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

谢谢.

Dar*_*rov 10

你可以使用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);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后使用OutputCache属性:

[OutputCache(CacheProfile = "MyProfile")]
public ActionResult Index()
{
   return View();
}
Run Code Online (Sandbox Code Playgroud)

并在web.config中:

<caching> 
    <outputcachesettings>             
        <outputcacheprofiles> 
            <clear /> 
            <add varybycustom="IsLoggedIn" varybyparam="*" duration="86400" name="MyProfile" /> 
        </outputcacheprofiles> 
    </outputcachesettings> 
</caching>
Run Code Online (Sandbox Code Playgroud)

  • 很高兴给[作者](http://visitmix.com/writings/using-varybycustom-with-outputcache-in-asp-net-mvc-to-support-caching-for-logged-in-users)信用;) (8认同)