Click here to Skip to main content
15,881,588 members
Articles / Web Development / ASP.NET
Article

ASP.NET Page Output Cache

Rate me:
Please Sign up or sign in to vote.
4.53/5 (27 votes)
30 Dec 2009Ms-PL4 min read 137.1K   1.6K   43   13
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.

ASP.NET
<%@ 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.
    • ASP.NET
      <%@ 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.
    • ASP.NET
      <%@ 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.
    • ASP.NET
      <%@ 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 > 
      ASP.NET
      <%@ 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.

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)


Written By
China China
Microsoft All-In-One Code Framework delineates the framework and skeleton of Microsoft development techniques through typical sample codes in three popular programming languages (Visual C#, VB.NET, Visual C++). Each sample is elaborately selected, composed, and documented to demonstrate one frequently-asked, tested or used coding scenario based on our support experience in MSDN newsgroups and forums. If you are a software developer, you can fill the skeleton with blood, muscle and soul. If you are a software tester or a support engineer like us, you may extend the sample codes a little to fit your specific test scenario or refer your customer to this project if the customer's question coincides with what we collected.
http://cfx.codeplex.com/

Comments and Discussions

 
Questionoutput cache Pin
Pankaj Kumar Choudhary15-Jan-15 3:31
Pankaj Kumar Choudhary15-Jan-15 3:31 
can anyone explain the use of Location="Any | Client | Downstream | Server | None | ServerAndClient " Shared, VaryByControl, VaryByCustom, VaryByHeader, VaryByParam, VaryByContentEncoding, CacheProfile, NoStore, SqlDependency in output cache
QuestionCache GridView? Pin
Pham Dinh Truong1-Apr-13 0:08
professionalPham Dinh Truong1-Apr-13 0:08 
QuestionDifferent Server and Client Expire times Pin
jmhmaine13-Feb-13 12:07
jmhmaine13-Feb-13 12:07 
QuestionThanks Pin
Saurabharoma28-Aug-12 1:53
Saurabharoma28-Aug-12 1:53 
GeneralBest Pin
muhammadmustajab3-Aug-12 0:15
muhammadmustajab3-Aug-12 0:15 
GeneralMy vote of 4 Pin
Shrilata Ellaboina21-Feb-12 19:39
Shrilata Ellaboina21-Feb-12 19:39 
QuestionIts nice ..... Pin
Shrilata Ellaboina21-Feb-12 19:37
Shrilata Ellaboina21-Feb-12 19:37 
GeneralMy vote of 3 Pin
Rakesh Aytha23-Nov-11 20:27
Rakesh Aytha23-Nov-11 20:27 
Generalreally nice demo Pin
Kunal_analyst29-Apr-11 4:05
Kunal_analyst29-Apr-11 4:05 
GeneralMy vote of 2 Pin
slakker7-May-10 4:26
slakker7-May-10 4:26 
GeneralRe: My vote of 2 Pin
sobo12330-Sep-13 18:29
sobo12330-Sep-13 18:29 
GeneralNice Demo Pin
Anurag Gandhi14-Jan-10 4:02
professionalAnurag Gandhi14-Jan-10 4:02 
GeneralVery good library of stuff Pin
Sacha Barber31-Dec-09 4:05
Sacha Barber31-Dec-09 4:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.