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

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

asp.net mvc - MVC3 custom outputcache

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

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

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...