65.9K
CodeProject is changing. Read more.
Home

ASP.NET MVC, Remove IIS Header Bloat

starIconstarIconstarIconstarIconstarIcon

5.00/5 (6 votes)

Jun 13, 2014

CPOL
viewsIcon

30088

Optimizing ASP.NET MVC HTTP responses to remove unnecessary and possibly dangerous information when using IIS

By default, if you create a new ASP.NET MVC project, you’re going to get a lot of bloat in the headers of any response from the page. None of it is necessary or helpful, and can even be harmful (it makes it very easy for potential attackers to identify the system, for example).

Here is the default ASP.NET project’s response to a request for a page:

Cache-Control:private

Content-Encoding:gzip

Content-Length:2616

Content-Type:text/html; charset=utf-8

Date:Wed, 11 Jun 2014 16:07:59 GMT

Server:Microsoft-IIS/8.0

Vary:Accept-Encoding

X-AspNet-Version:4.0.30319

X-AspNetMvc-Version:4.0

X-Powered-By:ASP.NET

The first thing we’ll want to remove is the X-AspNetMvc-Version header. To remove this, simply open your Global.asax.cs file to Application_Start, and add this code at the top:

MvcHandler.DisableMvcResponseHeader = true;

In addition, while we’re in the global file, we can also eliminate the "Server" header by adding a handler to PreSendRequestHeaders event like this:

        protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
        {
            HttpApplication app = sender as HttpApplication;
            if (app != null &&
                app.Context != null)
            {
                app.Context.Response.Headers.Remove("Server");
            }
        }

Next, we can remove the "X-AspNet-Version" header by adding a config key to Web.Config. Here is the key to add (under <system.web>):

    <httpRuntime enableVersionHeader="false" />

Lastly, we can remove the X-Powered-By by adding another confing key to Web.Config (under <system.webserver>):

    <httpProtocol>

      <customHeaders>

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

      </customHeaders>

    </httpProtocol>

After doing all of this, we end up with a nice and clean response:

Cache-Control:private

Content-Encoding:gzip

Content-Length:2616

Content-Type:text/html; charset=utf-8

Date:Wed, 11 Jun 2014 16:17:09 GMT

Server:Microsoft-IIS/8.0

Vary:Accept-Encoding