Preventing Caching

A common problem when creating ASP pages is that although the data usually comes 'live' from the database, the browser often caches that information. Although this can help to reduce the bandwidth usage for your site, it also means that if the user has loaded the page before, he/she could be viewing out of date or inaccurate information.

There are a number of ways around this. First, you can set

Response.Expires = -1

which means that the page will always expire, and the browser will load a new copy. Alternatively, you can set a date on which the page will expire:

Response.ExpiresAbsolute = "5 December 2001"

or, simply the number of seconds in the future:

Response.Expires = 1000 'expires after 1000 seconds

However, in situations such as a shopping cart, even this is not enough. You will find that if the user presses the back button on their browser, more often that not, it doesn't bother re-loading the page... which can cause problems if the user has just completed the order, and then goes back to a full shopping cart. To get around this, there is one last trick... add this code:

'date in the past...
Response.AddHeader "Expires", "Mon, 26 Jul 1997 05:00:00 GMT"
'always modified
Response.AddHeader "Last-Modified", Now & " GMT"
'HTTP/1.1
Response.AddHeader "Cache-Control", "no-cache, must-revalidate"
'HTTP/1.0
Response.AddHeader "Pragma", "no-cache"
'last ditch attempt!
Response.Expires = -1

This code adds a number of fields to the header information sent to the browser, and seems to be effective whatever the browser!

You might also like...

Comments

James Crowley James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audience ...

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning.” - Rich Cook