While functionality is the number one goal of Web development, performance seems to be a close second. After all, a site that isn't used serves no purpose. Caching frequently accessed Web page data is one way to positively impact a Web application's performance. ASP.NET includes caching support that is easily incorporated in your application to boost application performance.

ASP.NET 1.x provides three ways to incorporate caching in a Web application:

  • Page Output caching: allows you to cache the dynamically generated page content.
  • Page Fragment caching: caches portions of a Web page.
  • Page Data caching: programmatically caches data/objects within a Web page.
In this article, I will focus my attention on Page Output caching.

Page Output caching
Output caching is applicable when the contents of an entire page are relatively static so it may be cached. Caching frequently accessed pages can result in substantial throughput gains. The way it works is initial page requests are generated dynamically with all subsequent requests served from the cache. The result is an enormous performance gain with heavily used applications.

The main aspect of caching a page is the expiration date. It determines how long content will be retained in the cache before it is reloaded from the source. It is accessible via code or with the page-level OutputCache directive. It includes the Duration parameter for specifying how long an item will be cached (in seconds). Along with Duration, the OutputCache directive contains the following attributes:

  • Location
    : The location of the cache. Valid values include Any, Client, Downstream, None, Server, and ServerAndClient. The default value is Any.
  • CacheProfile
    : The name of the cache settings to associate with the page. It is an optional element with no default value.
  • NoStore
    : A Boolean value signaling whether to prevent secondary storage of sensitive data.
  • Shared
    : A Boolean value that determines whether user control output can be shared with multiple pages.
  • VaryByCustom
    : Any text that represents custom output caching requirements.
  • VaryByHeader
    : A semicolon-separated list of HTTP headers used to vary the output cache.
  • VaryByParam
    : A semicolon-separated list of strings used to vary the output cache.
The key elements used most frequently are Duration and VaryByParam, which allows you to create different page level caches based on parameters.

These parameters correspond to querystring values sent with HTTP GET requests or form parameters sent along with HTTP POST requests. When this attribute is set to multiple parameters, the output cache contains a different version of the requested document for each combination of specified parameters. Possible values include none, an asterisk (*), and any valid query string or POST parameter name.

Listing A
contains a basic approach to page level caching with a C# page that loads employee data from the venerable SQL Server Northwind database. The data is relatively static, so it is cached for five minutes. Listing B
contains the equivalent VB.NET code.

Listing A
<%@ OutputCache Duration="300" VaryByParam="none" %>

<%@ Import Namespace="System.Data.SqlClient" %>

<%@ Import Namespace="System.Data" %>

<%@ Page language="c#" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >

<html><head><title>Employees</title>

<script language="C#" runat="server">

private void Page_Load(object sender, System.EventArgs e) {

if (!this.IsPostBack) {

String cString = "Data Source=test;Initial Catalog=Northwind;User
 Id=sa;Password=;";
SqlConnectionconn = null;
SqlCommandcomm = null;
SqlDataAdaptersda = null;
DataSetds = new DataSet();
conn = new SqlConnection(cString);
comm = new SqlCommand("SELECT EmployeeID, LastName, FirstName, 
City, HomePhone, Title FROM dbo.Employees ORDER BY LastName", conn);
sda = new SqlDataAdapter(comm);
sda.Fill(ds);
dgCache.DataSource = ds;
dgCache.DataBind();

} }

</script></head>

<body>

<form id="frmTechRepublicCaching" method="post" runat="server">

<asp:DataGrid id="dgCache" AutoGenerateColumns="False"
 runat="server" Width="525px" Height="281px">

<Columns>

<asp:BoundColumnDataField="EmployeeID" Visible="False" />

<asp:BoundColumnDataField="LastName" HeaderText="Last" />

<asp:BoundColumnDataField="FirstName" HeaderText="First" />

<asp:BoundColumnDataField="Title" HeaderText="Title" />

<asp:BoundColumnDataField="City" HeaderText="City" />

<asp:BoundColumnDataField="HomePhone" HeaderText="Phone" />

</Columns>  

</asp:DataGrid>

</form></body></html>

Listing B
<%@ OutputCache Duration="60" VaryByParam="none" %>

<%@ Import Namespace="System.Data.SqlClient" %>

<%@ Import Namespace="System.Data" %>

<%@ Page language="vb" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >

<html><head><title>Employees</title>

<script language="vb" runat="server">

Sub Page_Load()

If Not (IsPostBack) Then

Dim cString As String
cString = "Data Source=test;Initial Catalog=Northwind;
User Id=sa;Password=;"

Dim conn As SqlConnection

Dim comm As SqlCommand

Dim sda As SqlDataAdapter

Dim ds As new DataSet()
conn = new SqlConnection(cString)
comm = new SqlCommand("SELECT EmployeeID, LastName, 
FirstName, City, HomePhone, Title FROM dbo.Employees ORDER
 BY LastName", conn)
sda = new SqlDataAdapter(comm)
sda.Fill(ds)
dgCache.DataSource = ds
dgCache.DataBind()

End If

End Sub

</script></head>

<body>

<form id="frmTechRepublicCaching" method="post" runat="server">

<asp:DataGrid id="dgCache" AutoGenerateColumns="False" runat="server"
 Width="525px" Height="281px">

<Columns>

<asp:BoundColumnDataField="EmployeeID" Visible="False" />

<asp:BoundColumnDataField="LastName" HeaderText="Last" />

<asp:BoundColumnDataField="FirstName" HeaderText="First" />

<asp:BoundColumnDataField="Title" HeaderText="Title" />

<asp:BoundColumnDataField="City" HeaderText="City" />

<asp:BoundColumnDataField="HomePhone" HeaderText="Phone" />

</Columns>  

</asp:DataGrid>

</form></body></html>

Comments

1

Degremont - 27/07/06

Hi,

In my web application I would like to add a cache.

<%@ OutputCache duration="1000" varybyparam="none" %>

All its works, but in French localization I have a barbaric word.

For example, when I use a french word : "Soirées", with cache it was written "Soirées".

Have you got an idea ?

» Report offensive content

2

harpreet - 06/11/06

hey in my application i am using a grid view and if i apply following line for cachiing then paging of grid and other links of grid stops working
WHY????????????????

<%@ OutputCache duration="1000" varybyparam="none" %>

» Report offensive content

3

rakesh - 22/10/07

Currrently I am using Session for maintaing User Id

I want to use cache,Its is possible to use that ,Give me Solution

» Report offensive content

4

Bob - 29/03/08

My web site http://www.lessonplansforfree.com uses a lot of user controls. What sucks about page output caching is that you can cache user controls.

Bob
http://www.lessonplansforfree.com

» Report offensive content

5

Bob - 29/03/08

In my above comment I meant to say "can't cache user controls".

Thanks,

Bob
http://www.lessonplansforfree.com

» Report offensive content

Leave a comment

You must read and type the 6 chars within 0..9 and A..F

* indicates mandatory fields.

5

Bob - 29/03/08

In my above comment I meant to say "can't cache user controls". Thanks, Bob http://www.lessonplansforfree.com ... more

4

Bob - 29/03/08

My web site http://www.lessonplansforfree.com uses a lot of user controls. What sucks about page output caching is that you can cache ... more

3

rakesh - 22/10/07

Currrently I am using Session for maintaing User Id I want to use cache,Its is possible to use that ,Give me Solution ... more

Log in


Sign up | Forgot your password?

  • Staff Microsoft shows off IE9 preview

    This week, highlights from Microsoft's MIX10 conference and more in the Roundup. Read more »

    -- posted by Staff

  • Chris Duckett IE9's H.264 vote killed Ogg

    In a split decision by the judges, the winner of the W3C/WHATWG video codec consensus is H.264, taking home the future of video playback on the internet while loser Ogg goes home with nothing but thoughts of what might have been. Read more »

    -- posted by Chris Duckett

  • Staff Google launches Apps Marketplace

    Google launches and app store, while Mozilla plans to re-write its open-source license. More of this week's news in the Roundup. Read more »

    -- posted by Staff

Most popular tags

What's on?

  • Optus Deal

    Broadband + home phone + PlayStation®3 in a single package price!