ASP.NET Output Cache Notes

This ASP.NET article explores the output cache. The output cache can result in extreme performance improvements.

Output cache. An output cache improves ASP.NET site performance.

We need to enable the output cache on master pages in code-behind C# files. Our web site uses a master page and content page system. We use output caching on ASP.NET master pages.



Example. First, 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 needs output caching enabled.


Example that sets Response.Cache: C#

protected void Page_Load(object sender, EventArgs e)

You can test the code by adding a timestamp to every page. Remember, everything that you do not carefully test may eventually break. Here's a way to tell your page to generate a timestamp each time your page is built or generated.

Example that sets Label Text: C#

protected void Page_Load(object sender, EventArgs e)
    Label1.Text = "Generated on " + DateTime.Now.ToString();



Discussion. In this example, the Page_Load method is always run when a page is not served from the output cache. However, if the page is not from the output cache, this code will update the timestamp.


Page contents. When you browse your page you should get an old timestamp if the page was recently loaded, even when you force a refresh in the browser. The above code assumes you have a Label control with ID of Label1 in your .aspx.

Note: Remember that output cache is a suggestion. Your ASP.NET process can be restarted and the cache can be cleared at any time.

So: Don't worry if the page is regenerated every 15 minutes, even if you put it in the output cache for one month.

What could go wrong? You could cache too much. Never use output caching when you need to do complex interactions with your visitor. There are subtle issues with query strings that are not covered here.


Summary. We used the output cache with master pages in ASP.NET. With this method, the server's CPU load should be greatly reduced. But 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. It can be disabled when debugging.