I have a .net 6.0 C# API (developed on a Mac using Kestrel server) that is returning server in the response header. All the solutions I have tried for are for pre-6 and are no longer relevant.
I have tried this in my Program.cs:
app.Use((ctx, next) => {
var headers = ctx.Response.Headers;
headers.Add("X-Frame-Options", "DENY");
headers.Add("X-XSS-Protection", "1; mode=block");
headers.Add("X-Content-Type-Options", "nosniff");
headers.Add("Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload");
headers.Remove("Server");
return next();
});
This does not remove server, but it is adding the other headers. If I add the Server property with blanks (e.g. headers.Add("Server", "");
) then the server name (Kestrel) is not shown, but the header property still appears. This probably achieves the objective, but I would rather it not appear at all.
ChatGPT (I know, but I tried it as a last resort), suggested
var host = new WebHostBuilder().UseKestrel(options => options.AddServerHeader = false).UseStartup<StartupBase>().Build();
but that gave a run time error Cannot instantiate implementation type 'Microsoft.AspNetCore.Hosting.StartupBase' for service type 'Microsoft.AspNetCore.Hosting.IStartup'..
As a lesser important side question, since removing Server is best practice, I wonder why the default functionality is to include it rather than omit it. Shouldn't the onus be to add it in? What would a use case for including that value be?
The correct syntax to use is:
builder.WebHost.UseKestrel(option => option.AddServerHeader = false);
The builder
variable is available in the default template generated by Visual Studio.
In the default template, it is generated as:
var builder = WebApplication.CreateBuilder(args);
where args
is the parameters passed to the Main
method. The builder
is then later used to generate the app
. Make sure to set the Kestrel options before the call to Build
that generates the app
.
Documentation for the KestrelServerOptions.AddServerHeader
property is available online.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With