In ASP.NET Core 1.0 every response will include the header Server: Kestrel
. I want to remove this header along with other header like X-Power-By
using middleware.
I know that we can remove Kestrel header in host configuration by setting the following but I want to do it using middleware (actually when we have Httpmodule we can do like this so I am learning same thing). I tried my bit it did not work.
new WebHostBuilder()
.UseKestrel(c => c.AddServerHeader = false)
Tried code:
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>();
}
}