How to avoid a web page from being cached in ASP.net

You can add the below code to the Page_Load() method of the page

Response.Expires =-1500;
Response.CacheControl = "no-cache";

Now let’s take a look at each of the line and what exactly they do

1. Response.ExpiresAbsolute=DateTime.Now.AddDays(-1d);

Response.ExpiresAbsolute specify when the page cache is going to be expired. By adding -1d, we are ensuring that it's always expired since we are referring to a date in the past.

2. Response.Expires

Response.Expires specifies the duration of time before a page that is cached on a browser expires. So by assigning a large negative number, it will always ensure that it expires immediatly after. Actually there is no need to specify both Response.ExpiresAbsolute and Response.Expires since which ever you define last will override the other.

3. Response.CacheControl = "no-cache";

The above line will tell browser to not to cache the page.

As far as I know, the above no caching mechanism works for many browsers.

1 comment:

Hire DOT NET Developers said...

Well, I have been searching this solution for a while because I can’t get a correct answer anywhere. But finally I found it when I searched about DOT NET Development Services and found this blog which is pretty awesome.