using System;
using System.Web;
namespace Common.Web.Modules.Http
{
/// <summary>
/// Sets custom headers in all requests (e.g. "Server" header) or simply remove some.
/// </summary>
public class CustomHeaderModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.PreSendRequestHeaders += OnPreSendRequestHeaders;
}
public void Dispose() { }
/// <summary>
/// Event handler that implements the desired behavior for the PreSendRequestHeaders event,
/// that occurs just before ASP.NET sends HTTP headers to the client.
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void OnPreSendRequestHeaders(object sender, EventArgs e)
{
//HttpContext.Current.Response.Headers.Remove("Server");
HttpContext.Current.Response.Headers.Set("Server", "MyServer");
}
}
}
I got hung up for a bit because I forgot to clear my browser cache after making config changes. If you don't do that and the file is in your local cache, it will serve it back to you with the original headers (duh).
This web.config setup works to remove all unnecessary headers from the ASP.NET response (at least starting from IIS 10):
<system.web>
<!-- Removes version headers from response -->
<httpRuntime enableVersionHeader="false" />
</system.web>
<system.webServer>
<httpProtocol>
<customHeaders>
<!--Removes X-Powered-By header from response -->
<clear />
</customHeaders>
</httpProtocol>
<security>
<!--Removes Server header from response-->
<requestFiltering removeServerHeader ="true" />
</security>
</system.webServer>
Please note that this hides all the headers for the "application", as do all the other approaches. If you e.g. reach some default page or an error page generated by the IIS itself or ASP.NET outside your application these rules won't apply. So ideally they should be on the root level in IIS and that sill may leave some error responses to the IIS itself.