Microsoft KB Archive/323290

= How to cache in ASP.NET by using Visual C# .NET =

Article ID: 323290

Article Last Modified on 3/27/2007

-

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

-



This article was previously published under Q323290





For a Microsoft Visual Basic .NET version of this article, see 811431.

IN THIS TASK
 * SUMMARY
 * MORE INFORMATION
 * Cache ASP.NET pages
 * Turn off client and proxy caching
 * Cache arbitrary objects in server memory
 * REFERENCES



SUMMARY
This step-by-step article describes how to control the caching of Web pages and data objects in ASP.NET. When you cache Web pages, you avoid re-creating information when you make a later request. Caching is an important technique for building high performance and scalable server applications. When you make the first request for the page, you can store data objects, pages, or part of the page to the memory. You can store these items on a Web server, on a proxy server, or on the browser.

back to the top



MORE INFORMATION
ASP.NET provides easier methods to control caching. You can use the @ OutputCache directive to control page output caching in ASP.NET. Use the HttpCachePolicy class to store arbitrary objects, such as datasets, to server memory. You can store the cache in applications such as the client browser, the proxy server, and Microsoft Internet Information Services (IIS). By using the Cache-Control HTTP Header, you can control caching.

For more information about ASP.NET output caching, click the following article number to view the article in the Microsoft Knowledge Base:

308375 How to control page output caching in ASP.NET by using Visual C# .NET

back to the top

Cache ASP.NET pages
You can use the @ OutputCache directive to cache, or you can cache programmatically through code by using Visual Basic .NET or Visual C# .NET. The @ OutputCache directive contains a Location attribute. This attribute determines the location for cached item. You can specify the following locations:
 * Any - This stores the output cache in the client's browser, on the proxy server (or any other server) that participates in the request, or on the server where the request is processed. By default, Any is selected.
 * Client - This stores output cache in the client's browser.
 * Downstream - This stores the output cache in any cache-capable devices (other than the origin server) that participate in the request.
 * Server - This stores the output cache on the Web server.
 * None - This turns off the output cache.

The following are code samples for the @ OutputCache directive and equivalent programmatic code.   To store the output cache for a specified duration

Declarative Approach: <%@ OutputCache Duration=&quot;60&quot; VaryByParam=&quot;None&quot; %>

Programmatic Approach: Response.Cache.SetExpires(DateTime.Now.AddSeconds(60)); Response.Cache.SetCacheability(HttpCacheability.Public);   To store the output cache on the browser client where the request originated

Declarative Approach: <%@ OutputCache Duration=&quot;60&quot; Location=&quot;Client&quot; VaryByParam=&quot;None&quot; %>

Programmatic Approach: Response.Cache.SetExpires(DateTime.Now.AddSeconds(60)); Response.Cache.SetCacheability(HttpCacheability.Private);   To store the output cache on any HTTP 1.1 cache-capable devices including the proxy servers and the client that made request

Declarative Approach: <%@ OutputCache Duration=&quot;60&quot; Location=&quot;Downstream&quot; VaryByParam=&quot;None&quot; %>

Programmatic Approach: Response.Cache.SetExpires(DateTime.Now.AddSeconds(60)); Response.Cache.SetCacheability(HttpCacheability.Public); Response.Cache.SetNoServerCaching;   To store the output cache on the Web server

Declarative Approach: <%@ OutputCache Duration=&quot;60&quot; Location=&quot;Server&quot; VaryByParam=&quot;None&quot; %>

Programmatic Approach: TimeSpan freshness = new TimeSpan(0,0,0,60); DateTime now = DateTime.Now; Response.Cache.SetExpires(now.Add(freshness)); Response.Cache.SetMaxAge(freshness); Response.Cache.SetCacheability(HttpCacheability.Server); Response.Cache.SetValidUntilExpires(true);   To cache the output for each HTTP request that arrives with a different City:

Declarative Approach: <%@ OutputCache duration=&quot;60&quot; varybyparam=&quot;City&quot; %>

Programmatic Approach: Response.Cache.SetExpires(DateTime.Now.AddSeconds(60)); Response.Cache.SetCacheability(HttpCacheability.Public); Response.Cache.VaryByParams[&quot;City&quot;] = true; For the VaryByCustom attribute, the VaryByHeader attribute, and the VaryByParam attribute in the @ OutputCache directive, the HttpCachePolicy class provides the VaryByHeaders property and the VaryByParams property, and the SetVaryByCustom method. </ul>

back to the top

Turn off client and proxy caching
To turn off the output cache for an ASP.NET Web page at the client location and at the proxy location, set the Location attribute value to none, and then set the VaryByParam value to none in the @ OutputCache directive. Use the following code samples to turn off client and proxy caching.

<ul>  Declarative Approach: <%@ OutputCache Location=&quot;None&quot; VaryByParam=&quot;None&quot; %> </li>  Programmatic Approach: Response.Cache.SetCacheability(HttpCacheability.NoCache); </li></ul>

back to the top

Cache arbitrary objects in server memory
ASP.NET includes a powerful, easy-to-use caching mechanism that you can use to store objects that require a lot of server resources to create in memory. The Cache class implements this method. Instances are private to each application and the lifetime is tied to the corresponding application. To cache the arbitrary objects in ASP.Net by using the Cache class, follow these steps: <ol> Create a new ASP.NET Web Application by using Visual C# .NET.</li> By default, WebForm1.aspx is created.</li>  In HTML view of WebForm1.aspx, replace the existing code with the following sample code: <%@ Import Namespace=&quot;System.Data&quot; %> <%@ Import Namespace=&quot;System.Data.SqlClient&quot; %>

<script language=&quot;C#&quot; runat=&quot;server&quot;>

void Page_Load(Object Src, EventArgs E) {

DataView Source;

// Retrieve the DataView object from Cache. If not exist, then add DataView object to the Cache.

Source = (DataView)Cache[&quot;MyDataSet&quot;];

if (Source == null) {

SqlConnection myConnection = new SqlConnection(&quot;Server=ServerName; database=Pubs; user id=UID; password=PWD;&quot;); SqlDataAdapter myCommand = new SqlDataAdapter(&quot;select * from Authors&quot;, myConnection);

DataSet ds = new DataSet; myCommand.Fill(ds, &quot;Authors&quot;);

Source = new DataView(ds.Tables[&quot;Authors&quot;]); Cache[&quot;MyDataSet&quot;] = Source;

CacheMsg.Text = &quot;Dataset created explicitly&quot;; }     else { CacheMsg.Text = &quot;Dataset retrieved from cache&quot;; }

// Binding the DataView object with DataGrid.

MyDataGrid.DataSource=Source; MyDataGrid.DataBind; }

<form method=&quot;GET&quot; runat=&quot;server&quot;>

<font face=&quot;Verdana&quot;>Caching Data

<ASP:DataGrid id=&quot;MyDataGrid&quot; runat=&quot;server&quot; Width=&quot;700&quot; BackColor=&quot;#ccccff&quot; BorderColor=&quot;black&quot; ShowFooter=&quot;false&quot; CellPadding=3 CellSpacing=&quot;0&quot; Font-Name=&quot;Verdana&quot; Font-Size=&quot;8pt&quot; HeaderStyle-BackColor=&quot;#aaaad&quot; />

<asp:label id=&quot;CacheMsg&quot; runat=&quot;server&quot;/>

Note Replace the values for,  , and   in the sample code for the SqlConnection object with your SQL Server Name, User ID, and Password. </li> On the Debug menu, click Start to run the application.

Note When you restart the application, the Cached object is re-created.</li></ol>

back to the top

<div class="references_section">