Preventing caching of page : Strategies in ASP.NET

Here I would discuss strategies to disable caching in your pages especially related to and MOSS 2007.

If you wanted to prevent caching in plain old HTML, you would use these directives

<meta http-equiv="Expires" content="0">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">

I wont explain these tags here. You can refer to W3C HTML specification. Rather I would focus on how

to insert these HTML tags while developing in ASP.NET and MOSS 2007 i.e. master - content pages.

1) If you using plain aspx pages you can directly put these tags under the

&lt;head&gt; section and you are done.

If you are using master - content pages, you can add this to master page but beware, this will prevent

caching of all the pages.

Usually you are looking to prevent the caching of single page which contains dynamic data.

In that case, you can use strategies given below.

If you are using MOSS 2007, and want to prevent the caching of a content page, there are two choices:

  • Create a new page layout which contains these tags and bind that page to this page layout.
    This way you can, create more pages which do not get cached using this layout.
  • Entirely detach the page from its layout using Sharepoint Designer. This way, the markup is copied to the
    aspx page itself and you can add these tags easily. However this is not a recommended procedure as this
    is not scalable.

2) Add a contentplaceholder inside the &lt;head&gt; in your master page. Then in
any pages that need these headers, populate the content control with
these meta tags. Other pages don't need to populate (or even have) the
content control.

I do this a lot and it's much easier

If you want to do this programmatically, you can put this line in a webpart or custom control :

Page.Master.FindControl("Content PlaceHolder").InnerHtml = < no caching tags>


This is a small piece of code, which programmatically adds the &lt;meta http-equiv="refresh" ... /&gt;

to the &lt;head&gt; page.

void DisableBrowserCaching(HtmlHead hdr)
Control ctrl = (Control)hdr;

string currGMT =
DateTime.Now.ToUniversalTime().ToLongDateString() +
" " + DateTime.Now.ToUniversalTime().ToLongTimeString() + "

HtmlMeta meta = new HtmlMeta();
meta.Name = "expires";
meta.Content = currGMT;

meta = new HtmlMeta();
meta.HttpEquiv = "pragma";
meta.Content = "no-cache";

meta = new HtmlMeta();
meta.HttpEquiv = "cache-control";
meta.Content = "no-cache";


You can use this code like this, in your controls or webparts

HtmlHead hdr = Master.Page.Header;

or if you are not using master pages, you can directly pass the Page.Header.

This works and, I think, is more general for the different browser
behaviors. Also, it allows me to set the behavior for any page, whether a
master page is involved or not.