Removing headers from the response

心不动则不痛 提交于 2019-12-01 02:44:42

The problem is each one is added at a different point:

  • Server: added by IIS. Not exactly sure if it can be turned off although you seem to have been to remove it using HttpModule .
  • X-AspNet-Version: added by System.Web.dll at the time of Flush in HttpResponse class
  • X-AspNetMvc-Version: Added by MvcHandler in System.Web.dll. It can be overridden so this one should be OK.
  • X-Powered-By by IIS but can be turned off as you said.

I think your best bet is still using HttpModules.

For the benefit of those who land here through a google/bing search:: Here's the summary of steps:

Step 1: Create a class that derives from IHttpModule (and IDisposable to clean up when we're done):

    public class MyCustomModule : IHttpModule, IDisposable
    {
         private HttpApplication _httpApplication
private static readonly List<string> HeadersToCloak = new List<string>
            {
                "Server",
                "X-AspNet-Version",
                "X-AspNetMvc-Version",
                "X-Powered-By"
            };
    ..
    }

Step 2: Get a reference to the intrinsic context in the IHttpModule.Init method, and assign an event handler to the PreSendRequestHeaders event:

public void Init(HttpApplication context)
        {
            _httpApplication = context;

            context.PreSendRequestHeaders += OnPreSendRequestHeaders;
        }

Step 3: Now the headers can be removed like so:

private void OnPreSendRequestHeaders(object sender, EventArgs e)
        {
            if (null == _httpApplication)
            {
                return;
            }

            if (_httpApplication.Context != null)
            {
                var response = _httpApplication.Response;
                HeadersToCloak.ForEach(header => response.Headers.Remove(header));
            }
        }

Step 4: Now register this module in your root web.config under the system.webserver (if running IIS 7.0 integrated mode more details here):

<configuration>
  <system.webServer>
    <modules>
      <add name="MyCustomModule" type="<namespace>.MyCustomModule "/>
    </modules>
  </system.webServer>
</configuration>

Hope this helps!

Nick Evans

If you're using IIS7 / Azure then have a look at this:

Removing/Hiding/Disabling excessive HTTP response headers in Azure/IIS7 without UrlScan

It shows the best way to disable these headers without using HttpModules.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!