Use of caching in ASP.NET web sites

Two types of caching

For most sites biggest factor in performance is network latency.

Second biggest is number of individual objects that browsers need to load to display page. Minimised number of such objects by combining multiple style sheets and javascript files, using text links rather than images, etc.

If browser needs to load 6+ objects then distribute these between different hostnames to allow browser to request them simultaneously.

Minimise bandwidth requirements by reducing size of web pages. Enable http compression, minify javascript and compress images, sounds, videos, etc.

Application caching

Process of storing data (not pages) in a cache object.

Cache object is available as property of the Page object.

Acts as application wide cache - not just a page specific cache, i.e. single cache object exists for entire application. Items in cache can be shared between users sessions and requests.

Using cache object

Use like Session or similar objects.

Assign objects to cache using key, and retrieve using this key.

Always verify that retrieved items are not null - value either has not been cached, or has expired.

if (Cache["Greeting"] != null)
Label1.Text = (String)Cach["Greeting"];
Label1.Text = "Hello, world!";

Normally used to cache files, database query results, etc.


Provides find grained control over cache expiration.

Parameters available for function include:

Cache.Insert("FileCache", File.ReadAllText("SourceFile.txt"), new CacheDependency(Server.MapPath("SourceFile.txt"));

can create multiple dependencies for single item by adding the CacheDependency objects to an AggregateCacheDependency object.

Page Output Caching

ASP supports page output caching, keeping a copy of the rendered page output in memory. If page show dynamic content, or is customised for individual users then don't want this form of caching.

Each page can be configured to be cached independently.

Manage via @ OutputCache directive at top of page mark-up. Available attributes:

Attribute Description
Duration Number of seconds to cache page - required if not using CacheProfile
Location OutputCacheLocation enumeration value - Any, Client, Downstream, Server, None, ServerAndClient
CacheProfile Name of cache settings to associate with page - default ""
NoStore Boolean determining whether to prevent secondary storage of sensitive information
VaryByParam Semicolon separated list of strings used to vary the output cache. These strings correspond values sent along with Get or Post request. The output cache contains a different version of the requested document for each of the strings. If you don't want to specify a parameter to vary cached content then use the value "none". To vary output cache by all parameter values use value "*". Either this or VarByControl must be provided for all ASP.NET pages featuring user controls. Example: <@OutputCache Duration="15" VaryByParam="search;category">
VaryByControl Used to vary user controls output cache. Must identify the ASP.NET generated name of control, e.g. <@OutputCache Duration="15" VaryByControl="ct100$MainContent$ChoiceDropDownList">
SqlDependency     Identifies set of database and table name pairs on which the page / control cache depends. The SqlCacheDependency class monitors these database entries and purges the cache when they change.
VaryByCustom Any text that represents custom caching requirements. If has value of browser, then cache varied by browser name and major version. If custom string provided, then override GetCaryByCustomString in applications Global.asax file.
VaryByHeader Semicolon separated list of HTTP headers used to vary output.


Location, CacheProfile and NoStore attributes cannot be used with user controls.

Shared attribute cannot be used with ASP.NET pages.

To cache page for 900 seconds, regardless of parameters provided:

<@ OutputCache Duration="900" VarsByParam="none" %>

Partial page caching

Move the part of the page you want to cache to a user control and add the @ OutputCache directive to it.

Programmatically Configuring Caching

Can make run-time caching decisions via the Response.Cache object.

Using substitution to update caches

As an alternative to using separate user controls for dynamic elements and configuring different caching policy for these controls, can use one of two cache substitution techniques:

Determining whether to return cached page prior to rendering

To control whether cached version of page is sued, or page is regenerated code should respond to ValidateCacheOutput event and set valid value to HttpValidationStatus attribute.

Then from Page.Load event handler call AddValidationCallback method and pass an HttpCacheValidationHandler object with you method, e.g.

protected void Page_Load(object sender, EventArgs e)
Response.Cache.AddValidationHandler(new HttpCacheValidateHandler(ValidateCacheOutput), null);

Creating cache output dependency

To create cache page output dependency call:

Configuring caching for application

Can configure caching profiles to be referenced from pages within application. Provides centralised configuration of caching. Create by adding <caching> <outputCacheSettings> <outputCacheProfiles> sections to <system.web> of configuration file:

<add name="OneMin" enabled="true" duration="60"/>

Caching profiles support most of the same properties as @ OutputCache directive.

Must provide name attribute to identify profile.

Can use enable attribute to disable profile if required.

Reference cache profile within page by using CacheProfile attribute of @ OutputCache directive.