Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC OutputCache based on Session values

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?

like image 390
harman_kardon Avatar asked Jul 25 '12 08:07

harman_kardon


1 Answers

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;
   }
like image 177
yayadavid Avatar answered Nov 03 '22 05:11

yayadavid