MVC OutputCache based on Session values
Asked Answered
G

3

6

Is it possible to vary the output cache in MVC based on certain values in the session? I've read a lot about using the varybycustom functionality and overriding GetVaryByCustomString in Global.asax but the session is not available at this point.

public override string GetVaryByCustomString(HttpContext context, string custom)
{
     if (custom == "somekey") 
         //Want to check the session here (but it isn't available).

     return base.GetVaryByCustomString(context, custom);
}

I understand this is because the Session isn't created until later in the request pipeline.

My concern is that without varying the cache based on the user's session, the page (which changes based on what the user has in the session, has additional HTML specific to that user etc) will get cached (as the URL is the same) and served by our load balancer, proxy servers etc. and then served to other requests with other people's session information on the page!

The reason the URL is the same is that the user comes in as a 'guest', enters some information (POST), this is validated and stored in the session and then they are re-directed back to the same page (which should now be specific to the user based on the session data).

The page itself should be cached normally because if a 'guest' visits the same URL, it should serve the same 'standard' page every time.

Is is possible to vary the caching in this way?

Globigerina answered 25/7, 2012 at 8:29 Comment(0)
P
3

If you want to personalize the cache output per user, it is better you set the Location to OutputCacheLocation.Client as below. More information here

   [OutputCache(Duration=3600, VaryByParam="none", Location=OutputCacheLocation.Client, NoStore=true)]
   public string GetName()
   {
         return "Hi " + User.Identity.Name;
   }
Parathyroid answered 9/9, 2013 at 10:7 Comment(0)
H
0

Would a Output Cache ActionFilter help at all?

Or perhaps you could refactor your view in to a layout page plus partial views for anonymous and authenticated sections, then utilize Partial Caching.

Homeomorphism answered 25/7, 2012 at 8:40 Comment(0)
B
0

You should look into "Donut Caching", but this isn`t supported by ASP.NET MVC 3, at least not out of the box. Fortunately somebody already solved this problem for you see MvcDonutCaching

I read that ASP.NET MVC 4 will include "Donut Hole Caching" out of the box, but i cant tell if it's in the current RC or not.

Benoit answered 25/7, 2012 at 9:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.