• You are here: 
  • Home
  • Prevent Client Side Caching with HttpModules

Prevent Client Side Caching with HttpModules

Posted on April 28th, 2004

I am attempting to build a totally anonymous feedback system here at work and so I needed to find a way to prevent clients from caching any data coming off the server.  I started out by just putting in the standard cache killing code in the actual pages I was using but then I realized that this didn’t prevent the image, css, and javascript files from being cached off the server.  So to solve this issue I just made a little HttpModule to prevent caching of any content coming off the server.  Here is the code:
    using System;
    using System.Web;
   
    namespace TT.Web.HttpModules
    {
         ///


         /// HttpModule to prevent caching 
         ///

         public class NoCacheModule : IHttpModule
        {
            public NoCacheModule()
            {
            }
    
            #region IHttpModule Members
    
            public void Init(HttpApplication context)
            {
                context.EndRequest += (new EventHandler(this.Application_EndRequest));
            }
    
            public void Dispose()
            {
            }
    
            private void Application_EndRequest(Object source, EventArgs e) 
            {
                HttpApplication application = (HttpApplication)source;
                HttpContext context = application.Context;
                context.Response.ExpiresAbsolute = DateTime.Now.AddDays( -100 );
                context.Response.AddHeader( “pragma”, “no-cache” );
                context.Response.AddHeader( “cache-control”, “private” );
                context.Response.CacheControl = “no-cache”;
            }
    
            #endregion
        }
    }

The last thing to try and tackle would be preventing the pages from showing up in history as well… but I doubt there is anything I can do about that.

Filed under .NET |

One Response to “Prevent Client Side Caching with HttpModules”

  1. C. v. Berkel Says:
    May 10th, 2004 at 12:29 pm

    Have you tried SmartNavigation?

    (This might provide what you’re looking for (although it’s IE 5.5+)

Leave a Reply