ASP.NET Core 8中通过中间件或IIS管理器移除Server Header无效
无法移除ASP.NET Core 8响应中的Server Header问题
我正尝试在ASP.NET Core 8应用中移除HTTP响应中的Server Header,查阅大量资料并尝试多种方法后均未成功,以下是尝试过的方案:
- 直接在管道中使用ASP.NET Core中间件:
app.Use(async (context, next) => { context.Response.OnStarting(state => { var httpContext = (HttpContext)state; httpContext.Response.Headers.Remove("Server"); return Task.CompletedTask; }, context); await next.Invoke(context); });
- 参考Stack Overflow帖子,添加Server Header存在性判断的中间件:
app.Use(async (context, next) => { context.Response.OnStarting(state => { var httpContext = (HttpContext)state; if (context.Response?.Headers?.ContainsKey("Server") ?? false) { httpContext.Response.Headers.Remove("Server"); } return Task.CompletedTask; }, context); await next.Invoke(context); });
尝试使用URL Rewrite模块配置(包含Server变量设置和出站规则配置),但未生效。
创建包含多种移除逻辑的自定义中间件:
namespace POCWebAppRewriteUrl { public class ResponseHeadersMiddleware { private readonly RequestDelegate _next; public ResponseHeadersMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { context.Response.Headers.Remove("Server"); context.Response.OnStarting(() => { context.Response.Headers.Remove("Server"); return Task.CompletedTask; }); context.Response.OnCompleted(() => { if (context.Response.Headers.ContainsKey("Server")) { context.Response.Headers.Remove("Server"); } return Task.CompletedTask; }); await _next(context); } } }
但在Postman中仍能看到响应中的Server Header(Postman响应显示该Header存在)。
注:我不想通过web.config文件解决该问题,此前在.NET Framework 4.7版本项目中曾使用如下配置,现正迁移至ASP.NET Core 8:
<rewrite> <outboundRules> <rule name="Remove Server"> <match serverVariable="RESPONSE_SERVER" pattern=".*"/> <action type="Rewrite" value="None"/> </rule> </outboundRules> </rewrite>
请问为何无法移除该Header?感谢解答。
内容的提问来源于stack exchange,提问作者Julio Escudero Cuesta
相关产品推荐
相关产品推荐

