我有一个在.net core 3.1中开发的azure web api。请求和响应工作正常。我正在尝试从 api 响应中删除服务器 header ,但到目前为止尚未成功。
Tried below things,
option 1) Added in programe.cs
static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>{webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.AddServerHeader = false;
}).UseStartup<Startup>();
});
option 2) Added in Configure method of startup.cs
app.Use(async (context, next) =>
{
context.Response.OnStarting(() =>
{
int responseStatusCode = context.Response.StatusCode;
if (responseStatusCode == (int)HttpStatusCode.Created)
{
IHeaderDictionary headers = context.Response.Headers;
StringValues locationHeaderValue = string.Empty;
if (headers.TryGetValue("Server", out locationHeaderValue))
{
context.Response.Headers.Remove("Server");
}
}
return Task.FromResult(0);
});
option 3) Added in Configure method of startup.cs
app.Use(async (context, next) =>
{
context.Response.Headers.Remove("Server");
await next();
}
Either of these did not worked in my case. Am i missing anything here?
Please provide your suggestions.
最佳答案
对于红隼: 尝试在 Program.cs 中设置 Kestrel 选项,如下所示。 Kestrel 服务器 header 在请求管道中添加得太晚。因此,无法通过 web.config 或中间件删除它。 注意:下面我使用UseKestrel而不是ConfigureKestrel。
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.UseKestrel(options => options.AddServerHeader = false)
});
对于 IIS:您需要在 web.config 中进行如下设置:
<configuration>
<system.webServer>
<security>
<requestFiltering removeServerHeader="true" />
</security>
<httpProtocol>
<customHeaders>
<remove name="X-Powered-By" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
希望有帮助。
关于azure - 如何从作为 azure web 应用程序托管的 web api core 3.1 响应中删除服务器信息 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62598590/