1

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?

NineBerry
  • 26,306
  • 3
  • 62
  • 93
danielc
  • 509
  • 6
  • 19
  • What is the order of the middlewares? Maybe you try to remove it first, and the header is readded later? Have you debugged the time and location when the header is added? – KifoPL Jan 15 '23 at 17:15
  • 2
    "ChatGPT (I know, but I tried it as a last resort)....", you beter use Google: https://www.google.com/search?q=remove+Server+header+from+response+c%23+Kestrel It shows that this question is a duplicate.... – Luuk Jan 15 '23 at 17:28

1 Answers1

3

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.

NineBerry
  • 26,306
  • 3
  • 62
  • 93
  • Thanks much! That did the trick. I had seen the google link referenced above and it was for 2.1 then 3.1 on IIS so it didn't meet my needs, but this did the trick. Much obliged! – danielc Jan 15 '23 at 21:56