Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

outputcache mvc3 only logged out user caching

Is there a way to use the OutputCache attribute to cache the results of only logged out users and reevaluate for logged in users example:

What I'd Like

[OutputCache(onlycacheanon = true)]
public ActionResult GetPhoto(id){
   var photo = getPhoto(id);
   if(!photo.issecured){
      return photo...
   }
   return getPhotoOnlyIfCurrentUserHasAccess(id);
   //otherwise return default photo so please don't cache me
}
like image 289
maxfridbe Avatar asked Mar 28 '12 05:03

maxfridbe


2 Answers

You can use the VaryByCustom property in [OutputCache].

Then override HttpApplication.GetVaryByCustomString and check HttpContext.Current.User.IsAuthenticated.

  • Return "NotAuthed" or similar if not authenticated (activating cache)
  • Guid.NewGuid().ToString() to invalidate the cache
like image 175
jgauffin Avatar answered Oct 26 '22 15:10

jgauffin


This is how I implemented the above.

In Global.asax.cs:

public override string GetVaryByCustomString(HttpContext context, string custom)
{
    if (custom == "UserId")
    {
        if (context.Request.IsAuthenticated)
        {
            return context.User.Identity.Name;
        }
        return null;
    }

    return base.GetVaryByCustomString(context, custom);
}

Usage in Output Cache Attribute:

 [OutputCache(Duration = 30, VaryByCustom = "UserId" ...
 public ActionResult MyController()
 {
    ...
like image 21
gls123 Avatar answered Oct 26 '22 15:10

gls123