Wednesday, October 6, 2010

Prevent browser caching of web pages in asp.net which works in all browsers (IE/Firefox..)

In this article i am going to explain how to prevent the browser caching of web pages in asp.net .It is the one of the biggest issue
every developer face . 

      Why browser caching ?
                           To speed up user experience on the web, most browsers implement a technology called caching. Caching allows information such as WebPages, images, and so on, to be saved on a user’s computer. If the user calls for a previously requested webpage, the browser is able to access the information more quickly by recalling it from a cache, rather than making another request to the site itself.
                         One side it is a advantage but when you display sensitive information it will be a big drawback .Recently we have found one problem in our current project .that is when user log in and after some operations sing out .if user click on back button it is still displaying logged in user .Hmmm..... We have tried different ways to handle the issue .But  we have faced issues with Firefox .

                        So i have decided to write logic in master page load event .And i have added some login in logout page .Here is the code.

Place  this code in master page  in load event
HttpContext.Current.Response.Cache.SetAllowResponseInBrowserHistory(false);  
            HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);  
            HttpContext.Current.Response.Cache.SetNoStore();
            Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
            Response.Cache.SetValidUntilExpires(true);
 




         In Logout page Load   add this code  
  


Response.AddHeader("Pragma", "no-cache");
            Response.CacheControl = "no-cache";
            Response.Cache.SetAllowResponseInBrowserHistory(false);
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetNoStore();
            Response.Expires = -1;
            Session.Abandon();
            ClientScript.RegisterClientScriptBlock(this.GetType(),"signout", "DisableHistory()", true );


  
write this code in logout mark up page






function DisableHistory() {
 
           window.history.forward(1);
       }
       function RedirectToHome() {
 
           setTimeout("window.location = 'Index.aspx'",0);
       }
     
   </script>
 

call this  RedirectToHome method in body onload of logout page 




<body onload ="RedirectToHome();">
 
Run the application.Have a fun …
 
 
 

2 comments:

  1. Great, I never knew this, thanks.

    buy cialis

    ReplyDelete
  2. Great writing! I want you to follow up to this topic!?!

    aromatherapy

    ReplyDelete