Cache Customized Pages

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

Hot Tip

LANGUAGES: C#

TECHNOLOGIES: Caching

 

Cache Customized Pages

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

 

By Jeff Prosise

 

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

 

The secret to per-session page caching is the @ OutputCache directive's VaryByCustom attribute. Here's an @ OutputCache directive you can include in an .aspx file to cache, for up to 10 seconds, a different version of the page 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 this method:

 

<script language="C#" runat="server">

  public override string GetVaryByCustomString

    (HttpContext context, string arg)

  {

      if (arg.ToLower () == "sessionid") {

          HttpCookie cookie =

           context.Request.Cookies["ASP.NET_SessionId"];

           if (cookie != null)

              return cookie.Value;

      }

      return base.GetVaryByCustomString (context, arg);

  }

</script>

 

GetVaryByCustomString is a mechanism for extending ASP.NET's page output cache. This implementation of GetVaryByCustomString, which overrides the one inherited from HttpApplication, responds to a VaryByCustom="SessionID" attribute in an @ OutputCache directive by returning the current session ID, if present. ASP.NET responds by caching different versions of the page if the session IDs differ. Note that GetVaryByCustomString extracts the session ID from the session cookie, not from the session's SessionID property. This is because the request has yet to be associated with a session when GetVaryByCustomString is called.

 

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

 

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

 

 

 

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish