Cache Customized Pages

Use the @ OutputCache directive's VaryByCustom attribute to store different versions of a page.

Jeff Prosise

October 30, 2009

2 Min Read
ITPro Today logo in a gray background | ITPro Today

Hot Tip

LANGUAGES:C#

TECHNOLOGIES:Caching

 

Cache Customized Pages

Use the @ OutputCache directive's VaryByCustom attributeto store different versions of a page.

 

By Jeff Prosise

 

You probably know already that you can configure ASP.NET'spage output cache to cache different versions of a page based on varying inputparameters and HTTP headers. But did you know you also can configure it tocache different versions of a page based on varying session IDs? Per-sessionpage caching is extraordinarily useful for caching pages customized forindividual users.

 

The secret to per-session page caching is the @ OutputCache directive's VaryByCustom attribute. Here's an @ OutputCache directive you can includein an .aspx file to cache, for up to 10 seconds, a different version of thepage for each session ID encountered:

 

<%@ OutputCache Duration="10"VaryByParam="None"

 VaryByCustom="SessionID" %>

 

For VaryByCustom="SessionID"to work, the application root must include a Global.asax file, containing thismethod:

 

  public override stringGetVaryByCustomString    (HttpContext context,string arg)   {      if (arg.ToLower ()== "sessionid") {          HttpCookiecookie =           context.Request.Cookies["ASP.NET_SessionId"];            if (cookie != null)               returncookie.Value;       }      returnbase.GetVaryByCustomString (context, arg);   }

 

GetVaryByCustomStringis a mechanism for extending ASP.NET's page output cache. This implementationof GetVaryByCustomString, whichoverrides the one inherited from HttpApplication,responds to a VaryByCustom="SessionID"attribute in an @ OutputCachedirective by returning the current session ID, if present. ASP.NET responds bycaching different versions of the page if the session IDs differ. Note that GetVaryByCustomString extracts thesession ID from the session cookie, not from the session's SessionID property. This is because the request has yet to beassociated with a session when GetVaryByCustomStringis called.

 

An unpleasant side effect of this technique is it doesn'twork with cookieless session state. Also note that the page won't be cacheduntil a user requests the page for the second time because the first requestlacks a valid session cookie.

 

Jeff Prosise is theauthor of several programming books, including ProgrammingMicrosoft .NET(Microsoft Press). He also is a co-founder of Wintellect (http://www.wintellect.com), a softwareconsulting and education firm that specializes in .NET.

 

 

 

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like