How To Control Page Output Caching in ASP.NET by Using Visual C# .NET

Article translations Article translations
Article ID: 308375 - View products that this article applies to.
This article was previously published under Q308375
Expand all | Collapse all

On This Page

SUMMARY

This article demonstrates how to use the @ OutputCache directive to control page output caching in ASP.NET with Visual C# .NET. You can use this technique to cache your site's most frequently accessed pages, which can substantially increase your Web server's throughput. The throughput is commonly measured in requests per second. Although the sample code in this article demonstrates how to use the Duration and VaryByParam attributes, the article also includes a brief description of other approaches that you can use with the @ OutputCache directive.

NOTE: It is not the intention of this article to describe all of the @ OutputCache directive attributes and their possible uses in detail. For more information, refer to the References section.


Requirements

  • Microsoft Windows 2000 or Windows XP
  • Microsoft .NET Framework
  • Microsoft Internet Information Server (IIS)
  • Microsoft ASP.NET

Introduction to the @ OutputCache Directive

To use the @ OutputCache directive to control page output caching, you simply add the directive to the top of the page. The Page.InitOutputCache method translates the directive into HttpCachePolicy class methods.

The @ OutputCache directive includes the following attributes and settings:
  • Duration: This attribute specifies how long an item is held in the cache. The value for Duration is listed in seconds.
  • VaryByParam: This attribute determines cache entries by Get or Post parameters. For example, if a QueryString variable named testVal is set for the VaryByParam attribute, every page request that contains a different value for testVal is cached in a separate page. The following code illustrates the syntax for the VaryByParam attribute:
    <%@ OutputCache Duration="Seconds" VaryByParam="testVal"%>
    						
    NOTE: You can specify an asterisk (*) so that all different versions of the item are cached. Also, you can specify "none" if only one version of a cached item exists.
  • Location: This attribute determines where the item is to be cached. You can specify the following locations:
    • Any
    • Client
    • Downstream
    • Server
    • None

    The following code illustrates the syntax for the Location attribute:
    <%@ OutputCache Duration="Seconds" Location="Client" %>
    					
  • VaryByCustom: This attribute contains the default setting Browser, which means that a different instance of an item is cached for each browser version that requests it. For example, both Microsoft Internet Explorer 5 and Internet Explorer 5.5 request the item. When VaryByCustom is set to Browser, a cache entry exists for each browser version. You cannot provide a string to control the caching for other custom scenarios. The string does not have any meaning unless you provide code to override the HttpApplication.GetVaryByCustomString method in the Global.asax file.

    The following code illustrates the syntax for the VaryByCustom attribute:
    <%@ OutputCache Duration="Seconds" VaryByCustom="string" %>
    					
  • VaryByHeader: This attribute allows you to specify a particular HTTP header value as criteria for determining different cache entries. The following code illustrates the syntax for the VaryByHeader attribute:
    <%@ OutputCache Duration="60" VaryByHeader="Accept-Language" %>
    					

Steps to Create the @ OutputCache Duration Sample

The following steps demonstrate how to use the Duration attribute for page output caching to specify how long to cache an item.
  1. Create a new Visual Basic ASP.NET Web Application project as follows:
    1. Open Visual Studio .NET.
    2. From the File menu, point to New, and then click Project.
    3. In the New Project dialog box, click Visual C# Projects under Project Types, and click ASP.NET Web Application under Templates. In the Name text box, type OutputCacheDemo, and then click OK.
  2. Create a new .aspx page in Visual Studio .NET as follows:
    1. In Solution Explorer, right-click the project node, click Add, and then click Add Web Form.
    2. In the Name text box, type OutputCacheDuration.aspx, and then click Open.
  3. Delete the default code that Visual Studio .NET adds to the page.
  4. Highlight the following code, right-click the code, and then click Copy. In Visual Studio .NET, click Paste as HTML on the Edit menu to paste the code into the .aspx page:
    <%@ OutputCache Duration="20" VaryByParam="none"%>
    <HTML>
       <HEAD>
       <script language="C#" runat="server">
       void Page_Load(object sender, EventArgs e) 
       {	
          Label1.Text = "Time: " + DateTime.Now.TimeOfDay.ToString();
       }
       </script>
       </HEAD>
       <body>
          <STRONG>@ OutputCache Duration Sample</STRONG>
          <hr>
          <br>
          <asp:Label id="Label1" runat="server">Label</asp:Label>
          <br>
       </body>
    </HTML>
    					
  5. From the File menu, click Save OutputCacheDuration.aspx to save the page.
  6. From the Build menu in the Integrated Development Environment (IDE), click Build.
  7. To run the sample, right-click OutputCacheDuration.aspx in Solution Explorer, and then click View in Browser.
  8. After the page appears in the browser, take note of the time that appears in the label.
  9. Refresh the page in the browser. Notice that the time is the same as it was previously. If you refresh the page after the 20-second duration setting expires, a newly cached version of the page is displayed.

    NOTE: If you are viewing the page in an external browser, you can press the F5 key to refresh the page. If you are viewing the page in the Visual Studio .NET IDE internal browser, you can right-click the page and then click Refresh to refresh the page.

Steps to Create the @ OutputCache VaryByParam Sample

The following steps demonstrate how to use the VaryByParam attribute for page output caching to allow for different cached versions of a page to exist based on the value of one of its QueryString variable values.
  1. Create a new .aspx page in Visual Studio .NET as follows:
    1. In the Solution Explorer, right-click the project node, click Add, and then click Add Web Form.
    2. In the Name text box, type OutputCacheVaryByParam.aspx, and then click Open.
  2. Delete the default code that Visual Studio .NET adds to the page by default.
  3. Highlight the following code, right-click the code, and then click Copy. In Visual Studio .NET, click Paste as HTML on the Edit menu to paste the code into the .aspx page:
    <%@ OutputCache Duration="20" VaryByParam="testVal"%>
    <HTML>
       <HEAD>
          <script language="C#" runat="server">
       void Page_Load(object sender, EventArgs e) 
       {	
          Label1.Text = "Time: " + DateTime.Now.TimeOfDay.ToString();
       }
       </script>
       </HEAD>
       <body>
          <P>
             <STRONG>@ OutputCache VaryByParam Sample</STRONG>
          </P>
          <P>
             <hr>
          </P>
          <P>
             <br>
             <asp:Label id="Label1" runat="server"></asp:Label>
             <br>
             <hr>
             <a href=http://yourservername/OutputCacheDemo/OutputCacheVaryByParam.aspx?testVal=123">testVal(123)</a>
             <br>
             <a href=http://yourservername/OutputCacheDemo/OutputCacheVaryByParam.aspx?testVal=345">testVal(345)</a>
          </P>
       </body>
    </HTML>
    						
    NOTE: You must modify the two hyperlinks in the preceding code to reflect the name of your Web server. In addition, you may notice that the VaryByParam attribute is set to vary, based on the value of the QueryString variable testVal. This causes the page output to be cached for each instance in which the QueryString variable value for testVal is the same.
  4. From the File menu, click Save OutputCacheVaryByParam.aspx to save the page.
  5. From the Build menu in the IDE, click Build.
  6. To run the sample, right-click OutputCacheVaryByParam.aspx in Solution Explorer, and then click View in Browser.
  7. After the page appears in the browser, click testVal(123). This causes the browser to browse back to the page but with the QueryString variable testVal set to "123". Take note of the time that appears.
  8. Click testVal(123) again. Notice that the time is the same as it was previously. The page output has been cached based on the testVal variable value.
  9. Click testVal(345). Notice that a new time appears on the page.
  10. Click testVal(345) again. Notice that the previous page output is cached and displayed in the browser.
  11. Click testVal(123) to return to the first instance. Notice that different page output cache versions appear, based on the supplied QueryString variable value.

Troubleshooting

  • When you use VaryByParam, be aware that changes to the QueryString variable's case result in additional cache entries.
  • Keep in mind that Duration is specified in seconds.
  • When you use VaryByCustom and override the HttpApplication.GetVaryByCustomString method in the Global.asax file, the default setting of Browser is used if no match is found for the custom string that is provided with the attribute.

REFERENCES

For more information on page output caching, refer to the following Microsoft Web sites:
GotDotNet Page Output Caching QuickStart Tutorial
Microsoft .NET Framework Software Development Kit (SDK)
http://msdn2.microsoft.com/en-us/library/ms950382.aspx

Caching ASP.NET Pages
http://msdn2.microsoft.com/en-us/library/xsbfdd8c(vs.71).aspx

@ OutputCache
http://msdn2.microsoft.com/en-us/library/hdxfb6cy(vs.71).aspx

Properties

Article ID: 308375 - Last Review: May 31, 2007 - Revision: 7.9
APPLIES TO
  • Microsoft ASP.NET 1.1
  • Microsoft ASP.NET 1.0
  • Microsoft Visual C# .NET 2003 Standard Edition
  • Microsoft Visual C# .NET 2002 Standard Edition
Keywords: 
kbcaching kbhowtomaster kbio KB308375

Give Feedback

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com