如何移除ASP.Net MVC默认的HTTP头?

205

我正在处理的MVC应用程序中,每个页面都会在响应中设置以下HTTP头:

X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
X-AspNetMvc-Version: 2.0

我该如何防止它们显示出来?


@PavelMorshenyuk 请问,您找到了去除服务器名称的方法吗?被接受的答案并没有去除服务器。 - neda Derakhshesh
12个回答

348

X-Powered-By是IIS中的自定义标头。自IIS 7以来,您可以通过将以下内容添加到web.config文件中来删除它:

<httpProtocol> <customHeaders> <clear /> </customHeaders> </httpProtocol>

请注意,这将删除所有自定义标头。

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

这个头部也可以根据您的需要进行修改,有关更多信息,请参阅http://www.iis.net/ConfigReference/system.webServer/httpProtocol/customHeaders


将以下内容添加到web.config中以去除X-AspNet-Version头部:

<system.web>
  <httpRuntime enableVersionHeader="false" />
</system.web>

最后,要删除 X-AspNetMvc-Version,请编辑 Global.asax.cs 并在 Application_Start 事件中添加以下代码:

protected void Application_Start()
{
    MvcHandler.DisableMvcResponseHeader = true;
}
你还可以通过 Global.asax.cs 中的 Application_PreSendRequestHeaders 事件在运行时修改标题。如果你的标题值是动态的,则这非常有用:
protected void Application_PreSendRequestHeaders(object source, EventArgs e)
{
      Response.Headers.Remove("foo");
      Response.Headers.Add("bar", "quux");
}

4
+1 - 出于好奇,你为什么要那样做?2)这会有任何负面影响吗? - BritishDeveloper
77
出于安全考虑,您需要这样做来混淆生成您的网页所使用的技术。这迫使黑客付出更多的努力。 - D'Arcy Rittich
24
这是一项出自安全审查的建议。最好的做法是不要宣传你的技术堆栈,因为这有助于黑客针对该平台的特定漏洞进行攻击。 - Paul Fryer
6
在 IIS 8 上,这不会移除 X-Powered-By 头信息。请参考其他答案以了解如何在 web.config 中实现此操作。 - Knelis
1
不要使用代码来删除响应头,这是不稳定的,参考链接: https://learn.microsoft.com/en-us/aspnet/aspnet/overview/web-development-best-practices/what-not-to-do-in-aspnet-and-what-to-do-instead#presend 应该使用web.config自定义头代替: https://www.saotn.org/remove-iis-server-version-http-response-header/#remove-server-response-header-with-an-outboundrule-url-rewrite-rule 我的解决方案:https://dev59.com/MHA75IYBdhLWcg3wOGLS#51639886 - mitaka
显示剩余6条评论

114
你也可以通过在global.asax文件中添加代码来删除它们:
 protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
 {
   HttpContext.Current.Response.Headers.Remove("X-Powered-By");
   HttpContext.Current.Response.Headers.Remove("X-AspNet-Version");
   HttpContext.Current.Response.Headers.Remove("X-AspNetMvc-Version");
   HttpContext.Current.Response.Headers.Remove("Server");
 }

31
在我的情况下,只有最后三个操作起作用了。对于 "X-Powered-By",我仍然需要使用 <system.webServer><httpProtocol><customHeaders><remove name="X-Powered-By" /></customHeaders><redirectHeaders><clear /></redirectHeaders></httpProtocol></system.webServer> - Frank van Eykelen
2
在我的情况下,上述任何标头都没有被删除。我正在使用.NET 4.0和IIS 7。感谢本主题中的其他评论。除了“服务器”这个最糟糕的情况外,我已成功删除所有不需要的标头。 - Farjad
5
对于不经过代码路径的内容文件/图片等,它是否有效? - Mark Sowul
你在“Server”里放了什么?应该是这样吗?Response.Headers.Remove("Server: Microsoft-IIS/7.0"); 还是应该只写“Server”?请帮忙。 - neda Derakhshesh
对于其他人来说,“PreSendRequestHeaders”实际上是预发送响应头,这似乎有些奇怪? - JDPeckham
1
HttpContext.Current在此事件中为null。(.net 4.7 vs2017) - JDPeckham

52

我在web.config中找到了这个配置,它是为Visual Studio创建的一个New Web Site...而设计的(与New Project...相对)。虽然问题是关于ASP.NET MVC应用程序的,但这仍然是一个选项。

<system.webServer>
  <httpProtocol>
    <customHeaders>
      <clear />
      <remove name="X-Powered-By" />
    </customHeaders>
   </httpProtocol>
</system.webServer>
更新: 此外,Troy Hunt有一篇文章标题为“嘘...不要让你的响应头太吵闹”,详细介绍了如何删除这些头文件,以及他的ASafaWeb工具用于扫描它们和其他安全配置。

5
最佳选择,但需要IIS7+。您无需清除它们...只需删除即可。此外,您可能还想将此添加到system.webserver以消除另一个漏洞: <security> <requestFiltering> <verbs> <add verb="OPTIONS" allowed="false" /> </verbs> </requestFiltering> </security> - felickz
我认为<clear/>元素清除所有标题,包括'X-Powererd-By',因此<remove/>元素是多余的。 - Jan H
@JanH,它只会撤销已经应用的任何自定义标头规则(通常来自父目录中的配置或服务器本身)。基本上,“clear”元素告诉IIS将自定义标头视为尚未添加任何影响所讨论的站点/应用程序的内容。 - Eric

37

.NET Core

为了移除Server响应头,在Program.cs文件中添加以下选项:

.UseKestrel(opt => opt.AddServerHeader = false)

对于 dot net core 1,在 .UseKestrel() 调用内添加选项。对于 dot net core 2,在 UseStartup() 后添加该行。

如果部署到 IIS 并要删除 X-Powered-By 标头,请编辑您的 web.config 文件,并在 system.webServer 标记内添加以下部分:

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

.NET 4.5.2

为了移除Server头信息,您需要在您的global.asax文件中添加以下内容:

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        string[] headers = { "Server", "X-AspNet-Version" };

        if (!Response.HeadersWritten)
        {
            Response.AddOnSendingHeaders((c) =>
            {
                if (c != null && c.Response != null && c.Response.Headers != null)
                {
                    foreach (string header in headers)
                    {
                        if (c.Response.Headers[header] != null)
                        {
                            c.Response.Headers.Remove(header);
                        }
                    }
                }
            });
        }

    }

早于 .NET 4.5.2 版本

将以下 C# 类添加到您的项目中:

public class RemoveServerHeaderModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.PreSendRequestHeaders += OnPreSendRequestHeaders;
    }

    public void Dispose() { }

    void OnPreSendRequestHeaders(object sender, EventArgs e)
    {
        HttpContext.Current.Response.Headers.Remove("Server");
    }
}

然后在你的web.config中添加以下<modules>部分:

<system.webServer>
    ....
 <modules>
    <add name="RemoveServerHeaderModule" type="MyNamespace.RemoveServerHeaderModule" />
 </modules>

然而,我遇到了一个问题,子项目无法找到这个模块。不好玩。

移除 X-AspNetMvc-Version 头信息

要移除任何 .NET 版本的 ''X-AspNetMvc-Version'' 标签,请修改您的 ''web.config'' 文件以包含:

<system.web>
...
   <httpRuntime enableVersionHeader="false" />
...
</system.web>

感谢微软让这变得难以置信的困难。也许这是你们的意图,以便可以跟踪全世界的IIS和MVC安装...


6
在当今社会,“最坏的做法”被认为是将“不安全”的选项作为默认设置,并且很难选择“安全”选项。很难相信微软仍然这么做。这让我想起了Windows默认隐藏常见文件扩展名的做法,以便无意中的用户点击病毒。我记得比尔·盖茨在2003年宣布了“默认情况下安全”的口号 - 那个想法到底发生了什么? - mike nelson
2
@mikenelson 如果这能让你感觉好一点,试图在nginx中删除Server标签同样困难 - 我最终不得不黑进源代码本身。 - Rocklan
关于RemoveServerHeaderModule,它在WebApi项目中不起作用。 - krypru
你最后一部分删除了X-AspNet-Version头,而没有删除X-AspNetMvc-Version头。 - Suncat2000

33

在IIS 7上隐藏您的ASP.NET MVC Web应用程序所述,您可以通过将以下配置部分应用于您的web.config文件来关闭X-AspNet-Version标头:

<system.web> 
  <httpRuntime enableVersionHeader="false"/> 
</system.web>

通过更改Global.asax.cs文件,您可以删除X-AspNetMvc-Version头,方法如下:

protected void Application_Start() 
{ 
    MvcHandler.DisableMvcResponseHeader = true; 
}

自定义标头所述,您可以通过将以下配置部分应用于您的web.config来删除“X-Powered-By”标头:

<system.webServer>
   <httpProtocol>
      <customHeaders>
         <clear />
      </customHeaders>
   </httpProtocol>
</system.webServer>

无法通过配置轻松删除“Server”响应头,但是您可以实现一个 HttpModule 来删除特定的HTTP头,如在IIS 7上伪装ASP.NET MVC Web应用程序如何从IIS7的响应头中删除Server、X-AspNet-Version、X-AspNetMvc-Version和X-Powered-By所述。

使用bkaid的答案,我能够删除“Server”头。IIS 8。 - tmorell
bkaid的回答没问题,但需要编码,所以我认为我描述的解决方案更方便,因为它是基于配置的。 - RonyK

16

Windows Azure 网站上删除标准服务器标头页面所示,您可以使用以下方式删除标头:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <clear />
      </customHeaders>
    </httpProtocol>
    <security>
      <requestFiltering removeServerHeader="true"/>
    </security>
  </system.webServer>
  <system.web>
    <httpRuntime enableVersionHeader="false" />
  </system.web>
</configuration>

这将移除服务器头(Server header)和 X- 头。

在我的 Visual Studio 2015 测试中本地运行良好。

其他参考资料:


7
在我的ASP.NET 4.5.3应用程序中添加removeServerHeader="true"后,出现了500错误。 - Rocklan
4
@LachlanB,这是在IIS 10中添加的:_IIS 10.0添加了removeServerHeader属性,以防止将HTTP服务器标头发送给远程客户端。_来源:https://www.iis.net/configreference/system.webserver/security/requestfiltering - SynerCoder
3
我喜欢Azure页面提供的是_截图_而不是代码块。他们竭尽全力让删除这些无用且有潜在风险的标签变得非常困难。此外,我不敢相信我要引用一个三年前的SO问题来纠正这个问题,而目前看起来还没有被修正的迹象。 - Synctrex
2
我认为这个Web.config没有移除X-AspNetMvc-Version头信息。要移除它,我们需要在Global.asax中添加一些内容。https://dev59.com/MHA75IYBdhLWcg3wOGLS#20739875 - Jan H

8
在Asp.Net Core中,您可以这样编辑web.config文件:
<httpProtocol>
  <customHeaders>
    <remove name="X-Powered-By" />
  </customHeaders>
</httpProtocol>

您可以在Kestrel选项中删除服务器标头:
            .UseKestrel(c =>
            {
                // removes the server header
                c.AddServerHeader = false;
            }) 

6

请查看这篇博客

不要使用代码来删除头信息,因为根据Microsoft的说法,这是不稳定的。

我的建议是:

<system.webServer>          
    <httpProtocol>
    <!-- Security Hardening of HTTP response headers -->
    <customHeaders>
        <!--Sending the new X-Content-Type-Options response header with the value 'nosniff' will prevent 
                Internet Explorer from MIME-sniffing a response away from the declared content-type. -->
        <add name="X-Content-Type-Options" value="nosniff" />

        <!-- X-Frame-Options tells the browser whether you want to allow your site to be framed or not. 
                 By preventing a browser from framing your site you can defend against attacks like clickjacking. 
                 Recommended value "x-frame-options: SAMEORIGIN" -->
        <add name="X-Frame-Options" value="SAMEORIGIN" />

        <!-- Setting X-Permitted-Cross-Domain-Policies header to “master-only” will instruct Flash and PDF files that 
                 they should only read the master crossdomain.xml file from the root of the website. 
                 https://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html -->
        <add name="X-Permitted-Cross-Domain-Policies" value="master-only" />

        <!-- X-XSS-Protection sets the configuration for the cross-site scripting filter built into most browsers. 
                 Recommended value "X-XSS-Protection: 1; mode=block". -->
        <add name="X-Xss-Protection" value="1; mode=block" />

        <!-- Referrer-Policy allows a site to control how much information the browser includes with navigations away from a document and should be set by all sites. 
                 If you have sensitive information in your URLs, you don't want to forward to other domains 
                 https://scotthelme.co.uk/a-new-security-header-referrer-policy/ -->
        <add name="Referrer-Policy" value="no-referrer-when-downgrade" />

        <!-- Remove x-powered-by in the response header, required by OWASP A5:2017 - Do not disclose web server configuration -->
        <remove name="X-Powered-By" />

        <!-- Ensure the cache-control is public, some browser won't set expiration without that  -->
        <add name="Cache-Control" value="public" />
    </customHeaders>
</httpProtocol>

<!-- Prerequisite for the <rewrite> section
            Install the URL Rewrite Module on the Web Server https://www.iis.net/downloads/microsoft/url-rewrite -->
<rewrite>
    <!-- Remove Server response headers (OWASP Security Measure) -->
    <outboundRules rewriteBeforeCache="true">
        <rule name="Remove Server header">
            <match serverVariable="RESPONSE_Server" pattern=".+" />

            <!-- Use custom value for the Server info -->
            <action type="Rewrite" value="Your Custom Value Here." />
        </rule>
    </outboundRules>
</rewrite>
</system.webServer>

明智但有缺陷的建议。我发现唯一删除 X-AspNetMvc-Version 的方法是通过代码实现。 - Suncat2000

4
为了完整起见,还有另一种方法可以使用regedit删除Server头。请参阅此MSDN博客
创建一个名为DisableServerHeader的DWORD条目,并在以下注册表键中将值设置为1。

HKLM\SYSTEM\CurrentControlSet\Services\HTTP\Parameters

我更希望找到一个适当的解决方案,使用Web.config不是好选择,因为它需要安装rewrite模块,即使安装了也不能真正删除头信息,只能将其清空。

如果这个方案可行的话,听起来对我的情况是一个不错的解决方案。我有30个网站,它们使用不同版本的 .net,因此需要3种不同的方法来删除头文件并更新所有这些网站中的代码。我宁愿使用配置设置或注册表而不是修改代码。 - mike nelson
我两天前成功应用了这个,效果很好。 - Rudey
这对我没用。我在添加密钥后重新启动了服务器。我有什么遗漏吗? - Noobie3001

3

您可以在Application_EndRequest()中更改任何标题或其他内容,请尝试以下操作

protected void Application_EndRequest()
{
    // removing excessive headers. They don't need to see this.
    Response.Headers.Remove("header_name");
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接