Home > .NET > Prevent Client Side Caching with HttpModules

Prevent Client Side Caching with HttpModules

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.

.NET

  1. C. v. Berkel
    May 10th, 2004 at 12:29 | #1

    Have you tried SmartNavigation?

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

  2. July 6th, 2010 at 08:34 | #2

    Thanks for that, just what I was looking for.

    this is useful too
    http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.1

  1. No trackbacks yet.