outputcache mvc3 only logged out user caching
Asked Answered
D

2

6

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
}
Desrochers answered 28/3, 2012 at 5:55 Comment(0)
F
8

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
Faugh answered 28/3, 2012 at 6:4 Comment(4)
That's the very thing I was missing thank you. I didn't realize null disabled caching.Desrochers
Didn't know it was available. Thank you :)Barytes
null does NOT disable the cache. I've tried that solution on the sample project and it just caches separately for authenticated and non authenticated users...Arianearianie
@Arianearianie You can return Guid.NewGuid().ToString() instead of null, which would make every request unique. But it would have some performance implications.Argument
H
4

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()
 {
    ...
Havstad answered 17/5, 2012 at 11:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.