Remove Etag and Last-Modified headers from IIS
Asked Answered
G

1

5

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?

Gillispie answered 11/10, 2010 at 14:20 Comment(0)
A
7

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.

Armillas answered 11/10, 2010 at 14:32 Comment(4)
Thanks, that's useful. However, it seems inefficient for IIS to add the headers, then have some code remove them again. I'd really prefer to remove them 'at source'. Any bright ideas? IIS doesn't make this easy.Gillispie
Those headers are added by the IIS core code, whose design doesn't expose functionality the same way as Apache. Using a module like this is very quick, probably quicker than having a lower-level header management feature.Armillas
Quite agree. I investigated removing the headers using an Isapi filter, but this seemed arcane and there's little information about it. We've recently adopted Akamai as a content delivery network, i'm looking into manipulating the headers at this level, which gives more granular control. Essentially the problem is still a lack of control in IIS.Gillispie
How does this work in IIS6, when Response.Headers throws and InvalidOperationException if not running in integrated mode?Chapple

© 2022 - 2024 — McMap. All rights reserved.