March 15, 2014

Disable Browser Cache in asp.net

So, I have an asp.net application and I want to disable browser caching. Well, to start with, we should have a good reason not to cache the application - caching is there for improving page loading speed. Okay, once there is a good enough reason to not to allow client side caching, we can do so by setting proper response headers in the page. These headers are

Cache-Control : no-cache
Cache-Control: s-maxage=0
Cache-Control : no-store
Cache-Control: must-revalidate
Expires : date time in the past

Now, we can either set these values either at the page level or at the application level. Doing it at the page level is easy - just run the code from the Page_Load event. Doing it at the application level is a bit difficult. If you are using the same master page for the whole site or have extended the Page class and created pages using the extended Page class then you can place the code in the appropriate Page_Load event. Note that, you can also set site / application wide response headers using IIS.

Here is the code to disable browser caching using asp.net.

  1. private void DisableCache()
  2. {
  3.     Response.Cache.SetCacheability(HttpCacheability.NoCache); //Cache-Control : no-cache, Pragma : no-cache
  4.     Response.Cache.SetExpires(DateTime.Now.AddDays(-1)); //Expires : date time
  5.     Response.Cache.SetNoStore(); //Cache-Control :  no-store
  6.     Response.Cache.SetProxyMaxAge(new TimeSpan(0, 0, 0)); //Cache-Control: s-maxage=0
  7.     Response.Cache.SetValidUntilExpires(false);
  8.     Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);//Cache-Control:  must-revalidate
  9. }

 

Here is the Response headers view in Firefox when the page is run.

image

0 comments:

Reference: Shahed Kazi at AspNetify.com