Online courses in ASP.NET MVC / Core, jQuery, Angular, and Design Patterns conducted by Bipin Joshi. Read more...
Learn ASP.NET MVC / Core, jQuery, Angular, and Design Patterns through our online training programs. Courses conducted by Bipin Joshi on weekends. Read more details here.

HOW TO: Prevent Caching of web forms by the browser

Introduction

Well...this is not a topic of long article as such but a commonly asked question.

"How can I prevent caching of my web form pages by the browser so that when user clicks on the Back button of the browser he gets the latest output from the server and not the cached one."

Solution

When you request a web form, ASP.NET processes it on the server and returns it back to the browser. Browsers generally keep cache of web pages they visit to improve performance and reduce network hits. That means when you navigate from one page to another and use Back button of the browser, you are given copy of the web form the browser cache and not from the server. Though this behavior is fine for most of the case in some you need to prevent browser from such caching. For example, you are developing a payment processing page where user enters credit card number and other details. Once the form is submitted it should not be cached on the client side. Pressing Back button should not display the old details like credit card number.

To solve this problem here is a quick solution:

Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetAllowResponseInBrowserHistory(false);

Add above two lines of code in the Page_Load event handler.

Here, we use two method of the Cache object.

  • SetCacheability
  • SetAllowResponseInBrowserHistory

The first method sets the Cache-Control HTTP header. This header controls how documents are cached on the cache capable devices.  The method accepts a parameter of enumeration type - HttpCacheability. This enumeration has several values such as - NoCache, Private, Public, Server, ServerAndNoCache and ServerAndPrivate. The setting of NoCache means that the response will not be cached on the client.

The second method SetAllowResponseInBrowserHistory indicates whether the response will be kept in browser History. Passing the value of false means the output will not be held in browser history.

Download

You can download a sample web application that illustrates how to use these methods.




Bipin Joshi is a software consultant, trainer, author and a yogi having 21+ years of experience in software development. He conducts online courses in ASP.NET MVC / Core, jQuery, AngularJS, and Design Patterns. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced Yoga way of life he also teaches Ajapa Meditation to interested individuals. To know more about him click here.

Get connected : Twitter  Facebook  Google+  LinkedIn

Posted On : 06 Mar 2005



Tags : ASP.NET Web Forms Performance