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
}
You can use the VaryByCustom
property in [OutputCache]
.
Then override HttpApplication.GetVaryByCustomString and check HttpContext.Current.User.IsAuthenticated
.
"NotAuthed"
or similar if not authenticated (activating cache) Guid.NewGuid().ToString()
to invalidate the cacheThis 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()
{
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With