C#Dot Net Perls

ASP.NET C#
Output Cache on Master Page

by Sam Allen

Problem

Enable output caching in ASP.NET on master pages in code-behind C# files. Your web site uses a master page and content page system. You may want to add a cache of the actual page HTML. Output caches can greatly improve server performance, but we can't use the directive tag in a master page. We want output caching on every content page.

C# Solution

You cannot add an OutputCache directive on a master page. You must do the caching instructions programmatically, in code. Every content page that uses the master page to have output caching enabled, but not specified explicitly each time. Here's the code to cache every content page.

protected void Page_Load(object sender, EventArgs e)
{
    // Set the cache expiration date as never, basically. In computers,
    // one month is essentially never.
    // Use the DateTime class for our expiration.
    Response.Cache.SetExpires(DateTime.Now.AddMonths(1));

    // HttpCacheability.Server means that the page will only be created once 
    // on the server. Private means that the client is also allowed to cache.
    Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);

    // Indicate that the client's cache is valid until the item expires.
    Response.Cache.SetValidUntilExpires(true);
}

How can I test it?

By adding a timestamp to every page. (Everything that you do not carefully test is probably broken or will break eventually.) Here's a way to tell your page to generate a timestamp each time your page is built or generated.

protected void Page_Load(object sender, EventArgs e)
{
    // Print out on the page the time the page was executed.
    // If when you load the page and this time is not NOW,
    // then the page was in the output cache.
    Label1.Text = "Generated on " + DateTime.Now.ToString();
}

It doesn't always work

Remember that the output cache is a suggestion to the server. Your ASP.NET process can be restarted and the cache can be cleared at any time. Don't worry if the page is regenerated every 15 minutes, even if you put it in the output cache for 1 month.

What could go wrong?

Never use output caching when you need to do complex interactions with your visitor. Additionally, there are subtle issues with query strings that I do not go over in this article. If you have a simple site that uses a master page, and you want to enable output caching for all content pages, this article is appropriate.

Discussion

With this method, the server's CPU load should be greatly reduced. However, your ASP.NET pages must be fast in the first place if you want a quick site. Finally, output caching sometimes makes debugging your application harder. There are workarounds and I will discuss them in additional articles on this site.

Dot Net Perls is dedicated to sharing code and knowledge. It has
© 2007-2008 Sam Allen. All rights reserved.

Ads by The Lounge