Prevent a single Asp.Net page from caching

Today I was asked by a colleague how to prevent a single asp.Net page from caching.
The answer is quite easy. Just use the page load event to handle caching logic.

C# version

protected void Page_Load(object sender, EventArgs e)
       {
           System.Web.HttpContext.Current.Response.Cache.SetExpires(DateTime.Now.AddYears(-1));
           System.Web.HttpContext.Current.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
           System.Web.HttpContext.Current.Response.Cache.SetNoStore();
           System.Web.HttpContext.Current.Response.Cache.SetNoServerCaching();
           System.Web.HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
       }

VB.NET version

Protected Sub Page_Load(sender As Object, e As EventArgs)
       System.Web.HttpContext.Current.Response.Cache.SetExpires(DateTime.Now.AddYears(-1))
       System.Web.HttpContext.Current.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches)
       System.Web.HttpContext.Current.Response.Cache.SetNoStore()
       System.Web.HttpContext.Current.Response.Cache.SetNoServerCaching()
       System.Web.HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache)
 
   End Sub

Comments (2) -

Well done! Thank you. We enjoyed reading your post and whole blog. Keep on running it.

Noah Frisch 4/15/2012 11:39:50 AM

Hello, I enjoy your weblog. Is there something I can do to get updates like a subscription or something? I'm sorry I am not familiar with RSS?

Add comment