Walkthrough: Using Output Caching to Enhance Web Site Performance

Performance is a critical aspect of any Web application. Decreasing the amount of processing a Web server must do to comply with individual requests results in quicker response times, the server's ability to handle more concurrent requests, and a reduced load on intermediate and back-end data systems.

One way to achieve better performance with ASP.NET is by using output caching to reduce server workload. Output caching is an optimization that reduces Web server response time.

Normally, when a browser requests an ASP.NET page, ASP.NET creates an instance of the page, runs any code in the page, runs database queries (if any), dynamically assembles the page, and then sends the resulting output to the browser. Output caching allows ASP.NET to send a pre-processed copy of a page rather than go through this process for each request. This difference cuts down the amount of processing the Web server does, which increases performance and enables greater scalability.

Tasks illustrated in this walkthrough include:

  • Caching pages, using either a page directive to have the entire page output cached, regardless of browser type, individual parameters, or data.

  • Using application-level cache profiles, a feature that enables you to define output caching settings for an entire application. Individual pages can associate themselves with profiles contained in your Web.config file. This enables you to control caching centrally instead of editing each page.

  • Caching based on individual parameters sent with the page.

Prerequisites

In order to complete this walkthrough, you will need:

  • Visual Web Developer (Visual Studio).

  • Microsoft .NET Framework version 2.0.

Creating the Web Site

If you have already created a Web site in Visual Web Developer (see Walkthrough: Creating a Basic Web Page in Visual Web Developer), you can use that Web site and go to the next topic in this walkthrough. Otherwise, create a new Web site and page by following these steps.

To create a file system Web site

  1. Open Visual Web Developer.

  2. On the File menu, click New Web Site. (In Visual Web Developer Express Edition, on the File menu, click New, and then click Web Site.)

    The New Web Site dialog box appears.

  3. Under Visual Studio installed templates, select ASP.NET Web Site.

  4. In the Location box, type the name of the folder where you want to keep the pages of your Web site.

    For example, type the folder name C:\WebSites.

  5. In the Language list, select the programming language that you prefer to work in.

  6. Click OK.

  7. Visual Web Developer creates the folder and a new page named Default.aspx.

Configuring Page-Level Caching

This procedure introduces you to basic page caching. In this procedure, you will add a Label control to your page that displays the time when the page was created, and then configure the page to be cached. By displaying the page's creation time you can see that the page request is fulfilled from the cache.

To configure page-level caching

  1. Open or switch to the Default.aspx page. (Alternatively, you can use any other page in your Web site.)

  2. Switch to Design view.

  3. From the Standard group in the toolbox, drag a Label control to your page, leaving the default name of Label1.

  4. Double-click a blank area of the page.

    The designer switches to the code editor and creates a Page_Load method.

  5. Add the following highlighted code to the method:

    Protected Sub Page_Load(ByVal sender As Object, _
            ByVal e As System.EventArgs)
         Label1.Text = System.DateTime.Now.ToString()
    End Sub
    
    protected void Page_Load(Object sender, System.EventArgs e)
    {
         Label1.Text = System.DateTime.Now.ToString();
    }
    
  6. Press CTRL+F5 to run the page.

    When the page appears in the browser, you will see the current date and time. Press your browser's refresh button and notice that the timestamp changes each time.

  7. Close the browser.

  8. Add the following @ OutputCache directive to the top of the page:

    <%@ OutputCache Duration="15" VaryByParam="none" %>
    

    This directive configures the page to be cached. The Duration attribute specifies that the page will remain in the cache for 15 seconds.

  9. Press CTRL+F5 to run the page again.

  10. Refresh the page several times.

    Notice that the time display is updated only every 15 seconds, regardless of how many times you refresh the browser. This is because the request is fulfilled from the cache until the duration time has elapsed, at which point the page code is executed again.

Setting Application-Level Caching

In the preceding procedure, you configured caching for an individual page. In some circumstances you might want to configure caching for all pages in your Web site. You might also want to establish different caching rules (profiles) and apply the cache profiles to sets of individual pages. Setting application-level caching enables you to change cache behavior from a single configuration file rather than editing the @ OutputCache directive of individual pages. In the following procedure, you will set up a simple cache profile and use it for the page that you were just working with.

To configure application-level caching

  1. If you already have a Web.config file, go to step 4.

  2. In Solution Explorer, right-click the name of your Web site, and then click Add New Item.

  3. In the Add Item dialog box, click Web Configuration File, and then click Add.

    Be sure that you use the name Web.config.

  4. Add the following XML as a child of the system.web element:

    <!-- caching section group -->
    <caching>
    <outputCacheSettings>
        <outputCacheProfiles>
            <add name="AppCache1" enabled="true" duration="60"/>
        </outputCacheProfiles>
    </outputCacheSettings>
    </caching>
    
  5. Save the file and then close it.

  6. Open or switch to the Web page you were working with, and then switch to Source view.

  7. Change the @ OutputCache directive to read as follows:

    <%@ OutputCache CacheProfile="AppCache1" VaryByParam="none" %>
    
  8. Press CTRL+F5 to run the page.

  9. Refresh the page a number of times.

    This time the date will remain the same for the duration specified in the cache profile, which is 60 seconds.

Caching Using Parameters

The @ OutputCache directive requires you to set the VaryByParam attribute, which until you now you have set to "none". The VaryByParam attribute enables you to configure caching so that ASP.NET stores different versions of a page depending on parameters such as query strings, form post values, request headers, and so on. Instead of caching different versions of a page, you can cache different versions of an individual control by using the VaryByControl attribute. For more information, see How to: Cache Multiple Versions of a User Control Based on Parameters.

For example, you can use cache parameters in a page that displays weather conditions for select cities, where the weather data is refreshed only every three hours. In this scenario, you want to cache a separate version of the page for each city. You can do so by setting the cache parameter to vary by a query string parameter.

In the following procedure, you will change the Label control you added to your page so that it displays the time with a colored background. You can change the color by using a TextBox control for entering a color name.

When you submit the page, the color you type is submitted as post data, and the color behind the Label control changes. When a new color is requested (when the page includes new post data), the page is regenerated and the timestamp is updated. However, subsequent requests for the same color will result in the cached page being returned (until the duration interval has been exceeded).

To cache based on parameters

  1. Open or switch to the page you have been working on.

  2. Switch to Design view.

  3. From the Standard group of the toolbox, drag a TextBox control onto the page and set its ID to Color.

  4. Drag a Button control onto the page, leaving the default name of Button1.

  5. Set the Button control's Text property to "Change Color".

    Double-click the Button control to create a Click event handler.

  6. Within the method, add the following highlighted code:

    Protected Sub Button1_Click(ByVal sender As Object, _ 
            ByVal e As System.EventArgs) Handles Button1.Click
        Label1.BackColor = _ 
            System.Drawing.Color.FromName(Server.HtmlEncode(Color.Text))
    End Sub
    
    protected void Button1_Click(Object sender, System.EventArgs e)
    {
        Label1.BackColor =  
            System.Drawing.Color.FromName(Server.HtmlEncode(Color.Text));
    }
    
  7. Set the defaultbutton attribute of the form element to "Button1".

    This causes the Click event handler for the button to be invoked when the ENTER key is pressed.

  8. Replace the @ OutputCache directive with the following version:

    <%@ OutputCache Location="Server" Duration="60" VaryByParam="Color" %>
    
  9. Press CTRL+F5 to run the page.

  10. Type a color name such as "red" or "blue" in the text box, and then click Change Color.

    ASP.NET caches a version of the page that uses the color you specify.

  11. Refresh the page a number of times.

    If you do not type in a new color name, the date and time will not change for at least one minute, as specified by the Duration attribute in your @ OutputCache directive.

  12. Enter a new color, such as "green" or "orchid" and then submit the page.

    This time you will see the time update along with the new color.

Next Steps

This walkthrough has illustrated basic concepts of caching ASP.NET pages. You might also want to explore these additional caching techniques:

  • Instead of using page declarations, specify caching programmatically. For example, in your Page_Load method you could access the HttpCachePolicy class (through Page.Response.Cache), and set values and behavior accordingly.

  • Cache data-bound pages so that they are regenerated only when the data they are dependent on has changed. For details, see Walkthrough: Using ASP.NET Output Caching with SQL Server.

See Also

Tasks

Walkthrough: Using ASP.NET Output Caching with SQL Server

How to: Cache Multiple Versions of a User Control Based on Parameters

Concepts

ASP.NET Caching Overview

Reference

@ OutputCache

HttpCachePolicy

VaryByParams