Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Etag and Last-Modified headers from IIS

Did you know you can prevent the revalidation of files in browser cache and subsequent 304 response by completely removing both the ETag and Last-Modifed response headers?

Of course, this is easy in Apache, but as clear as mud in IIS 6. Does anyone know how to remove both of these headers in IIS?

like image 944
David Merrilees Avatar asked Oct 11 '10 14:10

David Merrilees


1 Answers

A programmatic way is to use a HTTP module, something like this (based on a SO answer by Luke):

namespace HttpModules
{
    using System;
    using System.Web;

    public class RemoveExtraneousHeaderModule : IHttpModule
    {
        /// <summary>
        /// Initializes a module and prepares it to handle requests.
        /// </summary>
        /// <param name="context">Provides access to the request context.</param>
        public void Init(HttpApplication context)
        {
            context.PreSendRequestHeaders += this.OnPreSendRequestHeaders;
        }

        /// <summary>
        /// Disposes of the resources (other than memory) used by this module.
        /// </summary>
        public void Dispose()
        {
        }

        /// <summary>
        /// Event raised just before ASP.NET sends HTTP headers to the client.
        /// </summary>
        /// <param name="sender">Event source.</param>
        /// <param name="e">Event arguments.</param>
        protected void OnPreSendRequestHeaders(object sender, EventArgs e)
        {
            NameValueCollection headers = HttpContext.Current.Response.Headers;
            headers.Remove("Server");
            headers.Remove("ETag");
            headers.Remove("X-Powered-By");
            headers.Remove("X-AspNet-Version");
            headers.Remove("X-AspNetMvc-Version");
        }
    }
}

The module gets installed via web.config, under <system.web> for IIS 6 and under <system.webServer> for IIS 7.

like image 187
devstuff Avatar answered Sep 28 '22 03:09

devstuff