The HttpCachePolicy Class

Just as the OutputCache page directive provides a high-level API for implementing caching, a low-level API is available through the HttpCachePolicy class. This class is contained within the System.Web namespace. It uses HTTP headers to control the caching. The HttpCachePolicy class mirrors the functionality provided by the page directive. It also provides additional low-level control, comparable to the type of control provided for object caching.

To use the HttpCachePolicy class to control output caching, do not include an OutputCache directive in the page file. Instead, use the Response.Cache syntax, as shown in the highlighted lines in Example 18-21 (for VB.NET) or Example 18-22 (for C#). (Example 18-22 includes only the script block, since the HTML is identical to that in Example 18-21. Note that these examples are similar to Example 18-3 and Example 18-4.)

Example 18-21. Output caching using HttpCachePolicy Class in VB.NET, vbOutputCache-03.aspx

<%@ Page Language="VB" %>

<script runat="server">
   sub Page_Load(ByVal Sender as Object, _
               ByVal e as EventArgs)
      Response.Cache.SetExpires(DateTime.Now.AddSeconds(10))
      Response.Cache.SetCacheability(HttpCacheability.Public) lblMsg.Text = "This page was loaded at " & _ DateTime.Now.ToString("T") lblUserName.Text = Request.Params("username") lblState.Text = Request.Params("state") end sub </script> <html> <body> <form runat="server"> <h1>Output Caching</h1> <asp:Label id="lblMsg" runat="server"/> <br/> <br/> UserName:&nbsp;&nbsp;&nbsp; ...

Get Programming ASP .NET now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.