Tuesday, February 26, 2008

Preventing Web Caching in ASP.NET

We are working on a shopping cart application in ASP.NET. that needed to prevent web caching. The code is in VB.NET, since the best practice source we bought was VB.NET based.

With the proliferation of browsers, and the variety of ways that they interpret directives, a number of strategies have to be employed.

Caching can occur in any of the following locations:
  • Any – cache anywhere including client, server and proxy server.
  • Client – cache in client browser.
  • Downstream – any cacheable devices but not the original server that participates in the request.
  • Server – cache on the web server
  • None – no cache
(Please ignore the lack of indenting ... blogger kept losing my directives

Public Shared Sub NoCachePage(ByVal currentPage As System.Web.UI.Page)

' This will turn off the cache for the above locations

currentPage.Response.Cache.SetCacheability (Web.HttpCacheability.NoCache)
currentPage.Response.Cache.SetNoStore()
currentPage.Response.Cache.SetExpires (DateTime.Now().AddDays(-366))
currentPage.Response.Cache.SetMaxAge (
New TimeSpan(0))
currentPage.Response.Cache.AppendCacheExtension (
"must-revalidate, proxy-revalidate")

' This is to explicitly add to header to avoid being cached in the client browser, without the above code the page might still be cached on the server but just not in the client. For example cache is set to Server and the following codes are also added

Dim Expires As New Web.UI.HtmlControls.HtmlMeta()
Expires.Name =
"Expires"
Expires.Content =
"0"
currentPage.Header.Controls.Add(Expires)

Dim CacheControl As New Web.UI.HtmlControls.HtmlMeta()
CacheControl.Name =
"Cache-Control"
CacheControl.Content =
"no-cache"
currentPage.Header.Controls.Add(CacheControl)

Dim Pragma As New Web.UI.HtmlControls.HtmlMeta()
Pragma.Name =
"Pragma"
Pragma.Content =
"no-cache"
currentPage.Header.Controls.Add(Pragma)

End Sub

No comments: