如何在Asp.Net Core 2.2.1 Web App中删除服务器头?

fin*_*s10 0 c# response-headers kestrel kestrel-http-server asp.net-core

我正在使用Asp.Net Core 2.2.1。我正在尝试从响应中删除服务器标头。我尝试options.AddServerHeader = false;在内部添加ConfigureKestrel(),但仍未成功。请协助我解决问题。

这是我的代码:

Program.cs

    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args)
        {
            return WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .ConfigureKestrel((context,options) => {
                    // Set properties and call methods on options
                    options.AddServerHeader = false;
                });
        }
    }
Run Code Online (Sandbox Code Playgroud)

Web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <!-- To customize the asp.net core module uncomment and edit the following section. 
  For more info see https://go.microsoft.com/fwlink/?linkid=838655 -->
  <system.webServer>
    <security>
      <requestFiltering removeServerHeader="true" />
    </security>
    <handlers>
      <remove name="aspNetCore" />
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
    </handlers>
    <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="InProcess">
      <environmentVariables>
        <environmentVariable name="ASPNETCORE_HTTPS_PORT" value="44342" />
        <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
      </environmentVariables>
    </aspNetCore>
    <httpProtocol>
      <customHeaders>
        <remove name="X-Powered-By" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration>
Run Code Online (Sandbox Code Playgroud)

回应图片

在此处输入图片说明

谢谢,

阿卜杜勒

Sha*_*san 5

仅当您的应用程序在Kestrel上运行时,调用ConfigureKestrelwith options.AddServerHeader = false;才会删除服务器标头。在IIS / IISExpress上托管应用程序时,需要添加web.config具有以下设置的:

<configuration> 
  <system.webServer>
    <security>
      <requestFiltering removeServerHeader="true" />
    </security>
    <httpProtocol>
      <customHeaders>
        <remove name="X-Powered-By" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration>
Run Code Online (Sandbox Code Playgroud)

这条线<requestFiltering removeServerHeader="true" />可以解决问题。此外,如果愿意,您还可以删除自定义标题,例如X-Powered-By,方法是customHeadershttpProtocol

请确保您已启用请求过滤

在此处输入图片说明

我希望这有帮助。