Hiding Response Headers

Every once and a while I get a question that makes me think, hmm. Today I received one such question, and it was “How do I hide my server header information?”.

First, this is what you get as a default:

hmblmehearderswithouthidingthem

It looks like there are 4 things that need removing X-Powered-By, X-AspNet-Version, X-AspNetMvc-Version and Server.

The first 2 tags can be removed by editing the web.config of your application:

To remove the “X-AspNet-Version” tag, in <system.web> add:

<httpRuntime enableVersionHeader="false" />

To remove the “X-Powered-By”, in <system.webServer> add:

<httpProtocol>
  <customHeaders>
    <remove name="X-Powered-By" />
  </customHeaders>
</httpProtocol>

To remove the “X-AspNetMvc-Version” you need to edit you Global.asax.cs and add the following to the Application_Start() method:

MvcHandler.DisableMvcResponseHeader = true;

Removing the “Server” tag is a little harder. The only thing I could find was (and I spent around 30 seconds looking) was this great post from Stefan Goßner which I adapted to remove the header. It requires you install a custom Http Module into IIS. Here is the code:

using System;
using System.Web;

namespace ServerHeaders
{
    public class CustomServerHeaderModule : IHttpModule
    {
        public void Init(HttpApplication context)
        {            
            context.PreSendRequestHeaders += OnPreSendRequestHeaders;
        }
        public void Dispose() { }
        static void OnPreSendRequestHeaders(object sender, EventArgs e)
        {
            // remove the "Server" Http Header
            HttpContext.Current.Response.Headers.Remove("Server");
        }
    } 
}

I created a new class project for this class, then added a reference to the project from the web application. To wire up the handler I updated the <modules> tag to the following:

<modules runAllManagedModulesForAllRequests="true">
  <add name="CustomServerHeader" type="ServerHeaders.CustomServerHeaderModule" />
</modules>

Deploying to Windows Azure yields:

noheaders

THIS POSTING IS PROVIDED “AS IS” WITH NO WARRANTIES, AND CONFERS NO RIGHTS