O'Reilly logo

Programming ASP.NET, Second Edition by Dan Hurwitz, Jesse Liberty

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

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-24 (for VB.NET) or Example 18-25 (for C#). (Example 18-25 includes only the script block, since the HTML is identical to that in Example 18-24. Note that these examples are similar to Example 18-3 and Example 18-4.)

Example 18-24. 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; ...

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