Caching of web pages is an effective way of increasing performance while minimizing the use of precious server resources. ASP.NET supports various forms of caching:
Output caching: Output caching caches the output of a page (or portions of it) so that a page's content need not be generated every time it is loaded.
Caching objects in a page: While output caching is useful, a much more powerful and flexible approach would be to cache individual objects in your web application, rather than entire pages.
Smart caching with dependencies: The cache would automatically invalidate itself when some external events happen (such as the modification of a text file, and so on).
Time-based caching: Another technique for caching is based on time. For example, the cache can expire on a certain date, or it will only be available for a certain period of time. There are two ways in which you can use time-based caching--sliding and absolute expiration.
SQL cache dependency: SQL cache dependency is the ability to invalidate a database cache if the data in a table is changed.
To illustrate how caching works in ASP.NET, let's consider an example using output
caching. Assuming that you have an ASP.NET web form, add a new
directive to the ASP.NET form:
<%@ OutputCache Duration="15" VaryByParam="*" %> <%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm1.aspx.vb" Inherits="Caching.WebForm1"%>
OutputCache directive specifies the various criteria for caching the page. In this
example, the output of the page will be cached for 15 seconds. This means that if
the page is loaded again within the next 15 seconds, it is refreshed; the Web server will
serve the same content without needing to dynamically regenerate the page (and
thus avoiding access the database, if part of the content of the page is retrieved from
VaryByParam attribute specifies how the caching should be performed, based
on the query string supplied to the page. For example, if I used the following URL:
The query string passed to the page is
name=John&newsid=12. Now, suppose I
VaryByParam attribute to:
<%@ OutputCache Duration="15" VaryByParam="Name" %>
The page will then be cached according to the
Name key. This means that if I issue
requests using the following two URLs, the second request will still be from the cache,
as the cache will only be refreshed if the value of
The following URLs will cause the second request to be refreshed:
If you want to force the page to be regenerated if more than one key changes (such
NewsID), you simply add the
NewsID key into the
<%@ OutputCache Duration="15" VaryByParam="Name;NewsID" %>
In this case, this is equivalent to using a
*, which means all keys will cause the
page to be regenerated:
<%@ OutputCache Duration="15" VaryByParam="*" %>
If you want to cache the page regardless of query string, you can use the value
<%@ OutputCache Duration="15" VaryByParam="none" %>
Refer to my articles on ONDotnet.com for more information on caching: