Setting ASP.NET Cache control headers

asp.netwebforms

In my asp.net forms app. I'm trying to prevent caching of certain pages.
to do so I've set a series of cache control headers using Response.AppendHeader
e.g.

protected override void OnLoad(Eventargs e) 
{
...
Response.ClearHeaders();
Response.AppendHeader("Cache-Control","no-cache");
....
base.OnLoad(e);
}

Trouble is when I view my site and look at the Net tab in the Firefox console to view the request/response headers I see a behavior as follows:

  1. a POST request/response for the page1.aspx which triggers a redirect (to page2.aspx)
    the response here contains the correct headers.

  2. a GET request/response for page2.aspx
    associated response has the cache-control header just has a value 'pre-check=0'

That second request seems to allow the caching to happen for the page..
note: page1.aspx and page2.aspx both have the OnLoad logic I describe above. Also if I take some action on page2.aspx, the POST response will again have the correct headers.

What am I missing here? My expectation was that with the logic in OnLoad should mean that I always get the headers in the response and therefore 'always' get the current version of the page?

What I'm seeing is firefox loading it's cached version of the page.

I'm considering creating a random identifier in the request url to force the matter, but that seems a little heavy handed.

—–update—–
It seems that, this may be related to having the caching code in 'OnLoad'.
I've added these headers to the Page_Load() of the page and it works fine?
any thoughts.

Best Answer

Try swapping out Response.AppendHeader("Cache-Control","no-cache"); for

Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();

and make sure that you do not have an @ OutputCache directive and are not explicitly preventing cache control. See this MSDN page on SetCacheability and SetNoStore.