We will take a look at the OutputCache directive, which is by far the easiest way of caching content with ASP.NET. As you will see in our example, it doesn’t even require any code – only some minor changes to the markup of the page, and you’re good to go. In the next chapter, we will look into more ways of using the OuputCachce directive.
Here is a very simple example of a page which will show us the
difference between a cached page and a non-cached page. Try creating a
new project, and change the Default.aspx page to contain the following
markup:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Caching</title>
</head>
<body>
<form id="form1" runat="server">
<%= DateTime.Now.ToString() %>
</form>
</body>
</html>
This is all standard stuff, except the line with the DateTime. It simply
outputs the current date and time to the page. Try running the project
and reload the page a couple of times. As you will see, the time is
refreshed on each reload. Now, add the following line as line number 2
to our example:
<%@ OutputCache duration="10" varybyparam="None" %>
Run our project again, and reload the page a number of times. As you
will see, the time is only refreshed every 10 seconds. Adding caching to
your page is as simple as that! Now, the duration parameter is pretty
obvious - it tells the page how many seconds to cache the content. Each
time the page is requested, ASP.NET checks if the page is in the cache,
and if it is, whether or not it has expired. It's served from the cache
if it isn't expired - if it is, the page is removed from the cache and
the page is generated from scratch and then placed in the cache.
The varybyparam is a required parameter of the OutputCache directive. It
specifies a list of parameters which the the cache should be varied by.
For instance, if you set it to "p", the cache is now depending on the
value of the parameter p. Try changing our example to something like
this:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ OutputCache duration="10" varybyparam="p" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Caching</title>
</head>
<body>
<form id="form1" runat="server">
<%= DateTime.Now.ToString() %><br />
<a href="?p=1">1</a><br />
<a href="?p=2">2</a><br />
<a href="?p=3">3</a><br />
</form>
</body>
</html>
Now, run our example again, and try clicking the links. They each now
have their own timestamp, based on when you first accessed the page. The
cache is depending on the value of the p parameter! You can specify
multiple parameters by seperating them with a semicolon.