Outputcache mvc3 just exited user cache

Is there a way to use the OutputCache attribute to cache the results of only logged-out users and re-analyze them for registered users:

What I 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 } 
+6
source share
2 answers

You can use the VaryByCustom property in [OutputCache] .

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

  • Returns "NotAuthed" or similar if not authenticated (activates cache)
  • Guid.NewGuid().ToString() to invalidate cache
+8
source

Here is how I implemented 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); } 

Using the output cache attribute:

  [OutputCache(Duration = 30, VaryByCustom = "UserId" ... public ActionResult MyController() { ... 
+4
source

Source: https://habr.com/ru/post/911835/


All Articles