删除 ASP.NET 中显示技术堆栈的 HTTP 响应 headers 的最佳方法

Best way to remove HTTP response headers in ASP.NET that reveal technology stack

我需要从我的 ASP.NET MVC 3 网络应用程序中删除以下 header。

Server
X-AspNet-Version
X-AspNetMvc-Version
X-AspNetWebPages-Version
X-Powered-By

我找到了两个可行的选项。选项 1 更干净,实际上删除了服务器 header,但我试图找出是否有任何我应该担心的副作用。 哪个选项比另一个更好?每种方法的pros/cons是什么?

选项 1

Global.asax.cs >> Application_Start()

PreSendRequestHeaders += Application_PreSendRequestHeaders;

Global.asax.cs

protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
    HttpContext.Current.Response.Headers.Remove("Server");
    HttpContext.Current.Response.Headers.Remove("X-AspNetWebPages-Version");
    HttpContext.Current.Response.Headers.Remove("X-AspNet-Version");
    HttpContext.Current.Response.Headers.Remove("X-Powered-By");
    HttpContext.Current.Response.Headers.Remove("X-AspNetMvc-Version");
}

选项 2

Web.config >> 在 <system.web> 节点内(删除 X-AspNet-Version)

<httpRuntime enableVersionHeader="false" />

Web.config >> 在 <system.webServer> 节点内(删除 X-Powered-By)

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

Web.config >> 在 <system.webServer> 节点内(更改服务器的值,需要 URLRewrite)

<rewrite>
  <outboundRules rewriteBeforeCache="true">
    <rule name="Remove Server header">
      <match serverVariable="RESPONSE_Server" pattern=".+" />
      <action type="Rewrite" value="" />
    </rule>
  </outboundRules>
</rewrite>

Global.asax.cs >> Application_Start()(删除 X-AspNetMvc-Version 和 X-AspNetWebPages-Version)

MvcHandler.DisableMvcResponseHeader = true;
WebPageHttpHandler.DisableWebPagesResponseHeader = true;

我觉得第二版不错

根据你的描述和代码,我做了一个测试demo,将项目发布到IIS10后,发现响应头没有了 remove.You 发现x-Powered-by还在.

此外,根据HttpApplication.PreSendRequestHeaders Event API,您可以找到以下备注:

Do not use PreSendRequestHeaders with managed modules that implement IHttpModule. Setting these properties can cause issues with asynchronous requests. The combination of Application Requested Routing (ARR) and websockets might lead to access violation exceptions that can cause w3wp to crash. For example, iiscore!W3_CONTEXT_BASE::GetIsLastNotification+68 in iiscore.dll has caused an access violation exception (0xC0000005).