Understanding Caching Features in ASP.NET

Last Updated: Nov 08, 2025
8 min read
Legacy Archive
Legacy Guidance: This article preserves historical web development content. For modern .NET 8+ best practices, visit our Tutorials section.

Caching is a feature in ASP.NET that helps you create dynamic web pages efficiently. You know that dynamic web pages contain content that constantly changes and may even vary according to users. For example, a simple query to return a list of products from an online store will return products based on what the user inputs.

Users might request products from a particular manufacturer or products within a certain price range. The output of such queries varies based on user input to the query engine. However, the page layout, menus, and other links don't change. The header and footer stay the same. So if you cache the parts that provide data, that's enough. ASP.NET supports these types of caching.

When page content is similar for each request by any user, you can use caching to produce dynamic pages that load fast. The cached page gets stored in the server's memory, and this page gets served from memory without generating the page again. This provides faster response for requests made to a cached page.

Three Types of Caching

Caching can be done in three types. One is page caching, which lets you cache the entire page. Another is caching page elements, where some elements of the page are cached. The third is data caching, where the data available in the page is cached.

Page Caching with OutputCache

In page caching, the entire page gets cached. To achieve this, you need to use the OutputCache directive at the top of the page you want to cache. The syntax looks like this:

Basic OutputCache Directive
<%@ OutputCache Duration="6" VaryByParam="id" VaryByCustom="browser" %>

The attributes of this directive are Duration, VaryByParam, and VaryByCustom. The Duration attribute specifies how long the page output should be cached in seconds. After the specified duration, the cache gets removed and the page will be generated for the next request. If you specify 6 as the Duration value, the page output will be cached for 6 seconds before removal from cache.

Understanding VaryByParam

The VaryByParam attribute specifies the query string parameters to vary the cache. This is a required attribute. If the value is 'None', then the page output delivered is the same whatever the parameters for the query string. For example, if you specify the VaryByParam value as 'category', then the request to this page will get an output based on the query string 'category'.

VaryByParam Example
<%@ OutputCache Duration="6" VaryByParam="category" %>

<!-- Different cache for each URL: -->
<!-- http://www.yoursite.com/webpage.aspx?category=3 -->
<!-- http://www.yoursite.com/webpage.aspx?category=4 -->

The VaryByCustom tag displays content based on the browser used by the user. This gives page output for different browsers in different ways.

Fragment Caching

You know that the header and footer for a web page don't change in most web pages. To cache just the header and footer, you can use a technique called fragment caching. This allows a particular part of the web page to be served from cache.

For fragment caching, you need to put the content to be cached in a user control and add the caching directive at the top of the user control, not in the page that contains the user control. This caches the user control for a specific duration while the page serves dynamic content.

User Control Fragment Cache
<%@ Control Language="C#" %>
<%@ OutputCache Duration="300" VaryByParam="None" %>

<!-- This user control is cached for 5 minutes -->
<div class="site-header">
    <img src="logo.png" alt="Company Logo" />
    <nav>
        <a href="home.aspx">Home</a>
        <a href="products.aspx">Products</a>
        <a href="contact.aspx">Contact</a>
    </nav>
</div>

Data Caching

Data caching stores objects into memory and retrieves them for use in the web application. This enables you to use cached objects across all pages of the application. The lifetime of such cached objects matches the application itself. If the application restarts, all cached objects get destroyed. Here's a simple example:

Simple Data Cache
// Store value in cache
Cache["company"] = "ABC Inc";

// Retrieve from cache
if (Cache["company"] != null)
{
    Label1.Text = Cache["company"].ToString();
}

The code above stores the company name in cache. To retrieve this value, you need to first check whether that object exists in the cache and then use it.

Using the Insert Method

You can also use the Add or Insert methods of the Cache class to insert objects into cache. The following example shows you how to use the Insert method:

Cache Insert with Expiration
Cache.Insert(
    "company",
    sCompany,
    null,
    DateTime.Now.AddMinutes(3),
    TimeSpan.Zero
);

The first two parameters of the Insert method are the key and the object to be inserted into cache. The third parameter is called CacheDependency, which can be used to set dependency to a file. Null indicates there's no dependency.

The next parameter specifies the time at which the object should be removed from cache. The last parameter is called the sliding expiration parameter, which shows the time interval after which the object gets removed from memory.

Cache with File Dependency
// Create dependency on XML file
CacheDependency dependency = 
    new CacheDependency(Server.MapPath("config.xml"));

Cache.Insert(
    "appSettings",
    settings,
    dependency,
    DateTime.Now.AddHours(1),
    Cache.NoSlidingExpiration
);

// Cache clears when config.xml changes

Absolute vs Sliding Expiration

You can choose between two expiration models. Absolute expiration removes the cache at a specific time, regardless of how often it's accessed. Sliding expiration extends the cache lifetime each time someone accesses it.

Expiration Models
// Absolute expiration: expires at specific time
Cache.Insert(
    "news",
    newsData,
    null,
    DateTime.Now.AddMinutes(10),
    Cache.NoSlidingExpiration
);

// Sliding expiration: extends on each access
Cache.Insert(
    "userData",
    user,
    null,
    Cache.NoAbsoluteExpiration,
    TimeSpan.FromMinutes(20)
);

Caching Best Practices

By using the caching features of ASP.NET, you can provide powerful dynamic pages in a web application that delivers faster response to requested pages. Always check for null before using cached items. Use appropriate cache durations based on how often your data changes. Consider using cache dependencies when your cached data relies on external files or databases.

For personalized content, use fragment caching to cache common elements while keeping user-specific content dynamic. This gives you the best of both worlds: performance and personalization.

Quick FAQ

What does VaryByParam do in the OutputCache directive?

VaryByParam tells ASP.NET to create separate cache entries based on query string parameters. Setting it to 'None' caches one version for all requests. Setting it to a parameter name like 'category' creates different cached versions for each category value.

What's the difference between absolute and sliding expiration?

Absolute expiration removes the cache at a specific time regardless of access. Sliding expiration extends the cache lifetime each time someone accesses it. Use absolute for time-sensitive data and sliding for frequently accessed content.

How do cache dependencies keep data fresh?

Cache dependencies automatically invalidate cached items when related files or data change. When you tie cache to a file, any modification to that file clears the cache, forcing fresh data to load on the next request.

Back to Articles