Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cache ASP.NET page for anonymous users only

Tags:

Is there an easy way to cache ASP.NET whole page for anonymous users only (forms authentication used)?

Context: I'm making a website where pages displayed to anonymous users are mostly completely static, but the same pages displayed for logged-in users are not.

Of course I can do this by hand through code behind, but I thought there might be a better/easier/faster way.

like image 710
Arseni Mourzenko Avatar asked Jan 17 '10 16:01

Arseni Mourzenko


2 Answers

I'm using asp.net MVC, so I did this in my controller

if (User.Identity.IsAuthenticated) {
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.Cache.SetExpires(DateTime.Now.AddMinutes(-1));
    Response.Cache.SetNoStore();
    Response.Cache.SetNoServerCaching();
}
else {
    Response.Cache.VaryByParams["id"] = true; // this is a details page
    Response.Cache.SetVaryByCustom("username"); // see global.asax.cs GetVaryByCustomString()
    Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
    Response.Cache.SetCacheability(HttpCacheability.Server);
    Response.Cache.SetValidUntilExpires(true);
}

The reason I did it this way (instead of declaratively) was I also needed the ability to turn it on and off via configuration (not shown here, but there's an extra check in the if for my config variable).

You still need the vary by username, else you'll not execute this code when a logged in user appears. My GetVaryByCustomString function returns "anonymous" when not authenticated or the users name when available.

like image 188
WildJoe Avatar answered Oct 12 '22 05:10

WildJoe


You could use VaryByCustom, and use a key like username.

like image 24
Bruno Reis Avatar answered Oct 12 '22 07:10

Bruno Reis