O'Reilly logo

ASP.NET Cookbook by Geoffrey T. LeBlond, Michael A Kittel

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

13.4. Caching Pages Based on Developer-Defined Custom Strings

Problem

You have pages in your application that you want to cache but ASP.NET does not provide built-in support for the dependencies you need, such as browser type and full version number.

Solution

Add the @ OutputCache directive at the top of the .aspx file of each page you want to cache. Set the VaryByCustom attribute to the name of a custom string, such as "BrowserFullVersion“, as shown in the following code snippet:

 <%@ Page Language="vb" AutoEventWireup="false" 
         Codebehind="CH13CacheByCustomStringVB.aspx.vb" 
         Inherits="ASPNetCookbook.VBExamples.CH13CacheByCustomStringVB" %>
<%@ OutputCache Duration="10" VaryByParam="none" 
                               VaryByCustom="BrowserFullVersion" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
   ...
</html>

Next, override the GetVaryByCustomString method in Global.aspx.vb (Global.aspx.cs in C#) and write code that builds a unique string for the value you have assigned to the VaryByCustom attribute. Example 13-1 and Example 13-2 show VB and C# class files for overriding this method to return a full browser version number.

Discussion

ASP.NET provides the ability to control the caching of pages as a function of custom strings that you provide, which gives you the ability to control the caching by variations not directly supported by ASP.NET. In the example we use to illustrate this solution, we show how to cache pages based on the browser type, its major version number (integer portion of version ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required