Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'd like to use caching in my application but the data I'm returning is specific to the logged in user. I can't use any of the out of the box caching rules when I need to vary by user.

Can someone point me in the right direction on creating a custom caching attribute. From the controller I can access the user from Thread.CurrentPrincipal.Identity; or a private controller member that I initialize in the controller constructor _user

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
424 views
Welcome To Ask or Share your Answers For Others

1 Answer

You could use the VaryByCustom. In Global.asax override the GetVaryByCustomString method:

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);
    }
}

and then use the OutputCache attribute:

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

and in web.config:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...