Wednesday, October 31, 2007

Disabling ASP.NET Caching

Most web applications with authentication disable caching so after you logout, you can't click the back button to try and view pages that you shouldn't be accessing.

In ASP.NET, you can use the following code to disable caching
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1))
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.Cache.SetNoStore()

There are some other snippets you could try out too. Here's one:

Response.ClearHeaders();
Response.AppendHeader("Cache-Control", "no-cache"); //HTTP 1.1
Response.AppendHeader("Cache-Control", "private"); // HTTP 1.1
Response.AppendHeader("Cache-Control", "no-store"); // HTTP 1.1
Response.AppendHeader("Cache-Control", "must-revalidate"); // HTTP 1.1
Response.AppendHeader("Cache-Control", "max-stale=0"); // HTTP 1.1
Response.AppendHeader("Cache-Control", "post-check=0"); // HTTP 1.1
Response.AppendHeader("Cache-Control", "pre-check=0"); // HTTP 1.1
Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.1
Response.AppendHeader("Keep-Alive", "timeout=3, max=993"); // HTTP 1.1
Response.AppendHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT"); // HTTP 1.1

Another one to add directly to the HTML code on your page (this one has been known to not work on Firefox):

meta equiv="CACHE-CONTROL" content="NO-CACHE"

You'll probably want to test the code with all of your target web browsers.

1 comment:

Daniel said...

Thank you man,
it's working