65.9K
CodeProject is changing. Read more.
Home

ASP.NET Page Output Cache

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.53/5 (23 votes)

Dec 30, 2009

Ms-PL

4 min read

viewsIcon

139113

downloadIcon

1601

How to use the ASP.NET output cache.

Introduction

ASP.NET Caching is used to build high-performance, scalable ASP.NET web applications by storing responses in memory. On subsequent requests, the page code is not executed and the cached output is used to serve the request. In this article, we focus on ASP.NET Page Output Cache.

This is only a part of the Silverlight samples in the All-In-One Framework. You can get more samples from http://cfx.codeplex.com/.

Microsoft All-In-One Code Framework delineates the framework and skeleton of Microsoft development techniques through typical sample code in three popular programming languages (Visual C#, VB.NET, Visual C++). Each sample is elaborately selected, composed, and documented to demonstrate a frequently-asked, tested, or used coding scenario.

Background

By default, when we request an ASP.NET website, every request is processed by many stages, such as Page initialization, Load, Rendering, etc. This consumes a lot of resources on the server. Consider the following scenario: many customers browse ASP.NET websites for a news page and the news page won’t change for several hours. Based on a common route, when multiple customers request the same news page at almost the same time, ASP.NET will execute the same code to generate the response with the same news multiple times. This is a resource wasting process. Hence, we start thinking whether we can generate the response once and serve multiple customers with it. The answer is Cache.

Using the Code

ASP.NET provides a couple of caching methods: Output Cache (including Page level cache and User Control level cache) and the Cache API. In this article, we will discuss Output Cache. Output Cache has the advantage of being simple to implement, and is sufficient in most cases. It simply keeps a copy of the response that was sent to the client in memory and subsequent requests are then responded with the cached output until the cache expires, which incredibly improves the ASP.NET web application performance.

For ASP.NET Output Cache, ASP.NET uses @ OutputCache to declare many attributes to control the output caching policies of the ASP.NET page or a user control contained in a page.

<%@ OutputCache Duration="#ofseconds"
   Location="Any | Client | Downstream | Server | None | ServerAndClient "
   Shared="True | False"
   VaryByControl="controlname"
   VaryByCustom="browser | customstring"
   VaryByHeader="headers"
   VaryByParam="parametername" 
   VaryByContentEncoding="encodings"
   CacheProfile="cache profile name | ''"
   NoStore="true | false"
   SqlDependency="database/table name pair | CommandNotification"
%>

In this article, we will cover @OutputCache's Duration, VaryByCustom, VaryByParam, and VaryByControl attributes to cache the output of a page. For others, you can refer to http://msdn.microsoft.com/en-us/library/hdxfb6cy.aspx.

The walkthrough below demonstrates step-by-step how to use them. In the demo, we use date-time to determine whether a page is cached (in the PageLoad event, we write the date-time in a Label control named “lblResult”.):

  1. The Duration attribute
    • Add @OutputCache in the ASPX markup and specify the expiration time. In this case, we assign 10s for it. For example: OutputCache Duration="10" VaryByParam="none".
    • Run the ASP.NET web application and launch this page, and we will see that the date-time on the page won't change 10s when the page is reloading.
    • <%@ OutputCache Duration="10" VaryByParam="none" %>
      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
      <html xmlns="http://www.w3.org/1999/xhtml">
      <head runat="server">
          <title>OutPutCacheWithDuration</title>
      </head>
      <body>
          <form id="form1" runat="server">
          <div>
              <asp:Label ID="lblResult" runat="server"></asp:Label>
              <br />
              <br />
              <asp:Button ID="btnPostBack" runat="server" Text="Post Back"  />
              <p>
                  The page will be cached 10s, and then you can 
                         click Button to update datetime.
              </p>
          </div>
          </form>
      </body>
      </html>
  2. The VaryByControl attribute
    • Drag and drop a DropDownList in the page and add three items to it.
    • Add @OutputCache in the ASPX markup and specify the expiration time and VaryByControl attribute. For example: OutputCache Duration="1000" VaryByControl="ddlOption".
    • Run the ASP.NET web application and launch this page, we can see that the different items have their corresponding cache.
    • <%@ OutputCache Duration="1000" VaryByControl="ddlOption" %>
      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
      <html xmlns="http://www.w3.org/1999/xhtml">
      <head runat="server">
          <title>OutPutCacheWithVaryByControl</title>
      </head>
      <body>
          <form id="form1" runat="server">
          <div>
              <asp:Label ID="lblResult" runat="server"></asp:Label>
              <br />
              <br />
              <asp:DropDownList ID="ddlOption" runat="server" AutoPostBack="True" 
                         OnSelectedIndexChanged="ddlOption_SelectedIndexChanged">
                  <asp:ListItem Selected="True">Option One</asp:ListItem>
                  <asp:ListItem>Option Two</asp:ListItem>
                  <asp:ListItem>Option Three</asp:ListItem>
              </asp:DropDownList>
              <p>
                  The page will be rendered from cache basing 
                  on the selected item of DropDownList. 
                  The different item has corresponding cache. 
              </p>
          </div>
          </form>
      </body>
      </html>
  3. The VaryByCustom attribute
    • Add @OutputCache in the ASPX markup and specify the expiration time and VaryByControl attribute with the "browser" value. For example: OutputCache Duration="1000"VaryByCustom="browser"VaryByParam="none".
    • Run the ASP.NET web application and launch this page with IE and Firefox (or a browser with a different name, major version), and we will see that there is different cache versions for different browsers.
    • <%@ OutputCache Duration="1000" VaryByCustom="browser" VaryByParam="none" %>
      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
      <html xmlns="http://www.w3.org/1999/xhtml">
      <head runat="server">
          <title>OutPutCacheWithVaryByCustom</title>
      </head>
      <body>
          <form id="form1" runat="server">
          <div>
              <asp:Label ID="lblResult" runat="server"></asp:Label>
              <br />
              <br />
              <asp:Button ID="btnPostBack" runat="server" Text="Post Back" />
              <p>
                  The page will be rendered from cache basing 
                  on the version of browser, such as IE and FireFox.
              </p>
          </div>
          </form>
      </body>
      </html>
  4. The VaryByParam attribute
    • Add @OutputCache in the ASPX markup and specify the expiration time and VaryByParam attribute with an "id" value. For example: OutputCache Duration="1000" VaryByParam="id".
    • Run the ASP.NET web application and launch this page, and we can request it using a QueryString "id" with a different value.
    • For example:

      ~/OutputCacheWithParam.aspx?id=1
      ~/OutputCacheWithParam.aspx?id=2 > 
      <%@ OutputCache Duration="1000" VaryByParam="id" %>
      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
      <html xmlns="http://www.w3.org/1999/xhtml">
      <head runat="server">
          <title>OutPutCacheWithVaryByParam</title>
      </head>
      <body>
          <form id="form1" runat="server">
          <div>
              <asp:Label ID="lblResult" runat="server"></asp:Label>
              <p>
                  The page will be rendered from cache until 
                  the value of QueryString named "id" is
                  changed or Duration is expiration.
              </p>
          </div>
          </form>
      </body>
      </html>

Points of Interest

If there is any problem, you can take a look at the ReadMe.txt file in each sample project, which contains a step by step tutorial of how to build the project.

If you want to get more samples, please visit the Microsoft All-In-One Code Framework website.