Recipe 16.4. Caching Pages Based on Browser Type and Version


Problem

You have a page with static content that you want to cache, but the page is rendered differently for some browsers.

Solution

Add the @ OutputCache directive to the .aspx file of each page you want to cache with the VaryByCustom attribute set to "browser":

 <%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master"          AutoEventWireup="false"  CodeFile="CH16CacheByCustomStringVB.aspx.vb"  Inherits="ASPNetCookbook.VBExamples.CH16CacheByCustomStringVB"  Title="Cache By Custom String" %>     <%@ OutputCache Duration="10" VaryByParam="none"                        VaryByCustom="browser" %>

Discussion

The way in which a page is rendered often depends on the characteristics and version number of the browser making the request. ASP.NET handles most of this variation behind the scenes by sensing the browser type and its version and rendering the HTML and JavaScript in a suitable format.

The variation in a rendered page from one browser type to another can cause problems if you implement caching as described in Recipe 16.1. For example, if a request is made for a page of this type by Internet Explorer 6.x, the page is rendered and stored in the cache. If a request for the same page is made by a Netscape 4.x browser before the cached copy expires, the Internet Explorer 6.x version will be sent to the browser. This generally results in a poorly displayed or improperly functioning page.

ASP.NET provides the ability to cache browser-specific versions of the rendered page by setting the VaryByCustom attribute of the OutputCache element to "browser". When VaryByCustom is set to "browser", ASP.NET will check the browser name and major version of the browser making the page request (e.g., 4.x, 5.x, 6.x, etc.) to see if a copy of the rendered page is stored in the cache that matches them. If so, the cached version will be sent as the response. Otherwise, the page will be rendered as usual, stored in the cache, and delivered to the browser.

The only VaryByCustom attribute value that ASP.NET provides built-in support for is "browser"; however, with additional coding, this attribute can be used to control the caching of a page by any variation you choose. Recipe 16.4 provides an example of using the VaryByCustom attribute to cache a page based on the browser type and full version number.

The VaryByParam attribute is required even though it is not being used in this example. Setting the value to "none" disables the caching by parameter. If you fail to include the VaryByParam attribute, a parse error will result when the page is requested.


See Also

Recipes 16.1 and 16.4



ASP. NET Cookbook
ASP.Net 2.0 Cookbook (Cookbooks (OReilly))
ISBN: 0596100647
EAN: 2147483647
Year: 2003
Pages: 202

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net