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?