16.4. Caching Pages Based on Developer-Defined Custom Strings


You have pages in your application 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.


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“:

	<%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master"
		 Title="Cache By Custom String" %>
    <%@ OutputCache Duration="10" VaryByParam="none"
                       VaryByCustom="BrowserFullVersion" %>


Override the GetVaryByCustomString method in global.asax and write code that builds a unique string for the value you have assigned to the VaryByCustom attribute. Examples 16-1 and 16-2 show VB and C# GetVaryByCustomString method to return a full browser version number.


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 number), and its minor version number (the decimal portion of the version number).

The first ...

Get ASP.NET 2.0 Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.