Home   |   QuickStart Welcome   |   ASP.NET   |   Web Services   |   How Do I...?   
  |   I want my samples in...      

ASP.NET 2.0 Quickstart Tutorials

Page Output Caching

Output caching is a powerful technique that increases request/response throughput by caching the content generated from dynamic pages. Output caching is enabled by default, but output from any given response is not cached unless explicit action is taken to make the response cacheable.

To make a response eligible for output caching, it must have a valid expiration/validation policy and public cache visibility. This can be done using either the low-level OutputCache API or the high-level @ OutputCache directive. When output caching is enabled, an output cache entry is created on the first GET request to the page. Subsequent GET or HEAD requests are served from the output cache entry until the cached request expires. The output cache also supports variations of cached GET or POST name/value pairs.

The output cache respects the expiration and validation policies for pages. If a page is in the output cache and has been marked with an expiration policy that indicates that the page expires 60 minutes from the time it is cached, the page is removed from the output cache after 60 minutes. If another request is received after that time, the page code is executed and the page can be cached again. This type of expiration policy is called absolute expiration - a page is valid until a certain time.

The Output Cache Directive

The following example demonstrates a simple way to output cache responses using the @ OutputCache directive. The example simply displays the time when the response was generated. To see output caching in action, invoke the page and note the time at which the response was generated. Then refresh the page and note that the time has not changed, indicating that the second response is being served from the output cache.

VB Output Cache
Run Sample View Source

The following directive activates output caching on the response:

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

This directive simply indicates that the page should be cached for 60 seconds and that the page does not vary by any GET or POST parameters. Requests received while the page is still cached are satisfied from the cache. After 60 seconds, the page is removed from the cache; the next request is handled explicitly and caches the page again.

Of course, in the previous example, very little work is saved by output caching. The following example shows the same technique for output caching, but queries a database and displays the results in a grid.

VB Output Cache 2
Run Sample View Source

Vary By Parameters

In this, the application is modified slightly to allow the user to selectively query for authors in various states. This example demonstrates caching requests varying by the name/value pairs in the query string using the VaryByParam attribute of the @ OutputCache directive.

<%@ OutputCache Duration="60" VaryByParam="state" %>

For each state in the data set, there is a link that passes the desired state as part of the query string. The application then constructs the appropriate database query and shows authors belonging only to the selected state.

Note that the first time you click the link for a given state, it generates a new timestamp at the bottom of the page. Thereafter, whenever a request for that state is resubmitted within a minute, you get the original timestamp indicating that the request has been cached.

VB Output Cache VaryByParam
Run Sample View Source

SQL Cache Notification New in 2.0

In the previous example, the data was cached for 60 seconds, regardless of whether the data has changed in the database. SQL cache invalidation enables you to make the cache entry dependent on the database, so the cache entry will only be cleared when data in the database is changed. See the SQL Cache Notification page for more details.

Using the Disk Output Cache New in 2.0

With disk output cache, ASP.NET 2.0 can save cached responses to disk in addition to keeping them in memory. When the cached response is removed from the output cache due to memory pressure, it still remains on disk allowing a much larger set of pages to be cached. In addition, disk cached pages survive application restarts, enabling the cache to remain warm for when the application comes back up and begins serving requests. Disk caching is turned on by default for all pages, subject to a set of internally enforced restrictions. To turn disk caching off, specify DiskCacheable=false in the <%@ OutputCache %> directive on the page. In the sample below, the disk cache is turned on in configuration and a per-application disk usage limit is set to 2 megabytes. It is important to always set application quota for disk cache as it can easily fill up the disk otherwise.

VB Disk Output Caching
Run Sample View Source

Post-cache Substitution New in 2.0

In ASP.NET 1.0, pages that were mostly static but contained a small dynamic region, such as username or current time, were frequently forced to either not use caching or partition the page into multiple user controls cached with fragment caching. ASP.NET 2.0 enables these pages to take advantage of output caching, by allowing output cached pages to insert dynamic content on every request.

In the example below, the output cached page inserts a dynamic callback to a static method that returns the current date with the Response.WriteSubstitution API. This callback executes on every request, and the result gets inserted into the cached response chain that is served from output cache.

VB Post-Cache Substitution
Run Sample View Source

The following sample performs the same action as the sample above, but uses a asp:Substitution control to insert the dynamic content.

VB Substitution Control
Run Sample View Source

Using the Cache API

Applications that want more control over the HTTP headers related to caching can use the functionality provided by the System.Web.HttpCachePolicy class. The following example shows the code equivalent to the page directives used in the previous samples.

		
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Public);
C#

To make this a sliding expiration policy, where the expiration time out resets each time the page is requested, set the SlidingExpiration property as shown in the following code.

		
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetSlidingExpiration(true);
C#

Note: When sliding expiration is enabled (SetSlidingExpiration(true) ), a request made to the origin server always generates a response. Sliding expiration is useful in scenarios where there are downstream caches that can satisfy client requests, if the content has not expired yet, without requesting the content from the origin server.