How to disable caching in ASP.NET

You may want to disable caching in your web application for different reasons. One reason could be preventing sensitive data to be stored in client machine. Another reason is that giving users the latest version of the pages.

There are a couple of ways to disable caching. My favorite is using Response object. You can easily disable caching by adding these lines in your code-behind (Page_Load event of the page that you don’t want to be cached).

Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
Response.Expires = -1;
Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0

Another way is adding a page directive into your ASPX page.

<%@ OutputCache Location="None" VaryByParam="None" %>

You can also use a mix of web.config and page directives to centralize caching control. More information about leveraging web.config for caching control is here: https://msdn.microsoft.com/en-us/library/zd1ysf1y.aspx

References:

Leave a Reply