18.4 The HttpCachePolicy ClassJust 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:
<asp:Label
id="lblUserName"
runat="server"/>
<br/>
State:
<asp:Label
id="lblState"
runat="server"/>
</form>
</body>
</html>
Example 18-25. Output Caching Using HttpCachePolicy Class in C#, csOutputCache-03.aspx<%@ Page Language="C#" %>
<script runat="server">
void Page_Load(Object Source, EventArgs E)
{
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"];
}
</script>
The first highlighted line in Example 18-21 and Example 18-22 sets the cache duration to 10 seconds. It is equivalent to a Duration parameter in an OutputCache page directive. The second line corresponds to the Location parameter in the OutputCache directive. Table 18-4 compares the SetCacheability values, which are members of the HttpCacheability enumeration, with the Location values.
There are many other HttpCachePolicy methods and properties available. Some of the more common ones include:
|