Skip to main content

A simple ASP.NET C# Http Module that disables output caching of .aspx generated responses.

using System;
using System.Web;

namespace YourNameSpace.HttpModules
{
    /// <summary>
    /// Http module to instruct web browsers and proxy servers to not 
    /// store/cache .aspx file generated responses.
    /// </summary>
    /// <example>
    /// To enable this module, you will need to register it by creating a 
    /// new entry in your Web.config file.
    /// <code>
    ///     &lt;configuration&gt;
    ///         &lt;system.webServer&gt;
    ///             &lt;modules&gt;
    ///                 &lt;add name=&quot;DisableOutputCachingModule&quot; type=&quot;YourNameSpace.HttpModules.DisableOutputCachingModule&quot;/&gt;
    ///             &lt;/modules&gt;
    ///         &lt;/system.webServer&gt;
    ///     &lt;/configuration&gt;
    /// </code>
    /// </example>
    public class DisableOutputCachingModule : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.EndRequest += OnEndRequest;
        }

        public void Dispose()
        {
            // nothing to dispose...
        }

        private static void OnEndRequest(object sender, EventArgs e)
        {
            HttpContext context = ((HttpApplication)sender).Context;

            // skip if request is being redirected:
            if (context.Response.IsRequestBeingRedirected)
            {
                return;
            }

            // skip if not an .aspx page:
            if (!context.Request.Path.EndsWith(".aspx"))
            {
                return;
            }

            HttpResponse response = context.Response;
            HttpCachePolicy cache = response.Cache;

            // set the no caching headers:
            cache.SetCacheability(cacheability: HttpCacheability.NoCache);
            cache.AppendCacheExtension("no-store, must-revalidate");
            response.AppendHeader("Pragma", "no-cache");
            response.AppendHeader("Expires", "0");
        }
    }
}