Como remover o cabeçalho do servidor usando o middleware?
No ASP.NET Core 1.0, todas as respostas incluirão o cabeçalhoServer: Kestrel
. Eu quero remover este cabeçalho junto com outro cabeçalho comoX-Power-By
usando middleware.
Eu sei que podemos remover o cabeçalho Kestrel na configuração do host, definindo o seguinte, mas quero fazê-lo usando o middleware (na verdade, quando temos o Httpmodule, podemos fazer assim, então estou aprendendo a mesma coisa). Eu tentei a minha parte, não funcionou.
new WebHostBuilder()
.UseKestrel(c => c.AddServerHeader = false)
Código tentado:
public class HeaderRemoverMiddleware
{
private readonly RequestDelegate _next;
public HeaderRemoverMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext)
{
httpContext.Response.OnStarting(callback: removeHeaders, state: httpContext);
await _next.Invoke(httpContext);
}
private Task removeHeaders(object context)
{
var httpContext = (HttpContext)context;
if (httpContext.Response.Headers.ContainsKey("Server"))
{
httpContext.Response.Headers.Remove("Server");
}
return Task.FromResult(0);
}
}
public static class HeaderRemoverExtensions
{
public static IApplicationBuilder UseServerHeaderRemover(this IApplicationBuilder builder)
{
return builder.UseMiddleware<HeaderRemoverMiddleware>();
}
}