asp.net-mvc 如何删除 ASP.Net MVC 默认 HTTP 标头?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3418557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:24:39  来源:igfitidea点击:

How to remove ASP.Net MVC Default HTTP Headers?

asp.net-mvcsecurityhttp-headers

提问by Paul Fryer

Each page in an MVC application I'm working with sets these HTTP headers in responses:

我正在使用的 MVC 应用程序中的每个页面都在响应中设置这些 HTTP 标头:

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

How do I prevent these from showing?

我如何防止这些显示?

回答by RedFilter

X-Powered-Byis a custom header in IIS. Since IIS 7, you can remove it by adding the following to your web.config:

X-Powered-By是 IIS 中的自定义标头。从 IIS 7 开始,您可以通过将以下内容添加到您的web.config:

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

This header can also be modified to your needs, for more information refer to http://www.iis.net/ConfigReference/system.webServer/httpProtocol/customHeaders

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



Add this to web.configto get rid of the X-AspNet-Versionheader:

将此添加到web.config以摆脱X-AspNet-Version标题:

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


Finally, to remove X-AspNetMvc-Version, edit Global.asax.csand add the following in the Application_Startevent:

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

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


You can also modify headers at runtime via the Application_PreSendRequestHeadersevent in Global.asax.cs. This is useful if your header values are dynamic:

您也可以通过在运行时修改标题Application_PreSendRequestHeaders事件Global.asax.cs。如果您的标头值是动态的,这很有用:

protected void Application_PreSendRequestHeaders(object source, EventArgs e)
{
      Response.Headers.Remove("foo");
      Response.Headers.Add("bar", "quux");
}

回答by bkaid

You can also remove them by adding code to your global.asax file:

您还可以通过将代码添加到 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");
 }

回答by Kevin Hakanson

I found this configuration in my web.configwhich was for a New Web Site...created in Visual Studio (as opposed to a New Project...). Since the question states a ASP.NET MVC application, not as relevant, but still an option.

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

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

Update: Also, Troy Hunt has an article titled Shhh… don't let your response headers talk too loudlywith detailed steps on removing these headers as well as a link to his ASafaWebtool for scanning for them and other security configurations.

更新:另外,Troy Hunt 有一篇名为Shhh的文章......不要让你的响应头大声谈论删除这些头的详细步骤以及指向他的ASafaWeb工具的链接,用于扫描它们和其他安全配置。

回答by RonyK

As described in Cloaking your ASP.NET MVC Web Application on IIS 7, you can turn off the X-AspNet-Version header by applying the following configuration section to your web.config:

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

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

and remove the X-AspNetMvc-Version header by altering your Global.asax.cs as follows:

并通过如下更改 Global.asax.cs 来删除 X-AspNetMvc-Version 标头:

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

As described in Custom Headers You can remove the "X-Powered-By" header by applying the following configuration section to your web.config:

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

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

There is no easy way to remove the "Server" response header via configuration, but you can implement an HttpModuleto remove specific HTTP Headers as described in Cloaking your ASP.NET MVC Web Application on IIS 7and in how-to-remove-server-x-aspnet-version-x-aspnetmvc-version-and-x-powered-by-from-the-response-header-in-iis7.

没有简单的方法可以通过配置删除“服务器”响应标头,但您可以实现HttpModule删除特定 HTTP 标头,如在IIS 7 上隐藏您的 ASP.NET MVC Web 应用程序how-to-remove-server- x-aspnet-version-x-aspnetmvc-version-and-x-powered-by-from-the-response-header-in-iis7

回答by Rocklan

.NET Core

.NET 核心

To remove the Serverheader, within the Program.csfile, add the following option:

要删除Server标头,请在Program.cs文件中添加以下选项:

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

For dot net core 1, put add the option inside the .UseKestrel() call. For dot net core 2, add the line after UseStartup().

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

To remove X-Powered-Byheader, if deployed to IIS, edit your web.config and add the following section inside the system.webServer tag:

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

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

.NET 4.5.2

.NET 4.5.2

To remove the Serverheader, within your global.asaxfile add the following:

要删除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);
                        }
                    }
                }
            });
        }

    }

Pre .NET 4.5.2

.NET 4.5.2 之前

Add the following c# class to your project:

将以下 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");
    }
}

and then within your web.config add the following <modules> section:

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

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

However I had a problem where sub-projects couldn't find this module. Not fun.

但是我遇到了一个问题,子项目找不到这个模块。不好玩。

Removing X-AspNetMvc-Version header

删除 X-AspNetMvc-Version 标头

To remove the ''X-AspNetMvc-Version'' tag, for any version of .NET, modify your ''web.config'' file to include:

要删除 ''X-AspNetMvc-Version'' 标记,对于任何版本的 .NET,修改您的 ''web.config'' 文件以包括:

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

Thanks Microsoft for making this unbelievably difficult. Or maybe that was your intention so that you could track IIS and MVC installs across the world ...

感谢微软让这难以置信的困难。或者这可能是您的意图,以便您可以跟踪世界各地的 IIS 和 MVC 安装......

回答by Darxtar

In Asp.Net Core you can edit the web.config files like so:

在 Asp.Net Core 中,您可以像这样编辑 web.config 文件:

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

You can remove the server header in the Kestrel options:

您可以在 Kestrel 选项中删除服务器标头:

            .UseKestrel(c =>
            {
                // removes the server header
                c.AddServerHeader = false;
            }) 

回答by Eric Dunaway

As shown on Removing standard server headers on Windows Azure Web Sitespage, you can remove headers with the following:

在 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>

This removes the Server header, and the X- headers.

这将删除服务器标头和 X-标头。

This worked locally in my tests in Visual Studio 2015.

这在我在 Visual Studio 2015 中的测试中在本地工作。

回答by Rudey

For the sake of completeness, there is another way to remove the Serverheader, using regedit.

为了完整起见,还有另一种方法可以Server使用 regedit删除标题。

See this MSDN blog.

请参阅此 MSDN 博客

Create a DWORD entry called DisableServerHeader in the following Registry key and set the value to 1.

HKLM\SYSTEM\CurrentControlSet\Services\HTTP\Parameters

在以下注册表项中创建一个名为 DisableServerHeader 的 DWORD 条目并将值设置为 1。

HKLM\SYSTEM\CurrentControlSet\Services\HTTP\Parameters

I'd rather find a proper solution using the Web.config, but using <rewrite>is not good because it requires the rewrite module to be installed, and even then it won't really remove the header, just empty it.

我宁愿使用 Web.config 找到一个合适的解决方案,但使用<rewrite>并不好,因为它需要安装重写模块,即使这样它也不会真正删除标题,只是清空它。

回答by mitaka

Check this blogDon't use code to remove headers. It is unstable according Microsoft

检查此博客不要使用代码删除标题。根据微软的说法它是不稳定的

My take on this:

我对此的看法:

<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 clickHymaning. 
                 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>

回答by Emdadul Sawon

You can change any header or anything in Application_EndRequest()try this

您可以Application_EndRequest()尝试更改任何标题或任何内容

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