11

I am migrating a WebApi from .net5 to .net6. It's going fairly well, but have run into the problem of how to configure Kestrel during startup. The following code is from the Main method of the Program.cs file:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddVariousStuff();
builder.Host
.ConfigureWebHostDefaults(webBuilder =>
{
    webBuilder.ConfigureKestrel(serverOptions =>
    {
        serverOptions.Limits.MaxConcurrentConnections = 100;
        serverOptions.Limits.MaxConcurrentUpgradedConnections = 100;
        serverOptions.Limits.MaxRequestBodySize = 52428800;

    });


});
var app = builder.Build();
app.UseStuffEtc();
app.Run();

The app startup crashes with the following exception:

System.NotSupportedException: ConfigureWebHost() is not supported by WebApplicationBuilder.Host. Use the WebApplication returned by WebApplicationBuilder.Build() instead.

If I remove anything related to ConfigureWebHostDefaults, then app starts no problem. Am unable to figure out how roll with the new .net6 Kestrel server startup config.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
brando
  • 8,215
  • 8
  • 40
  • 59

1 Answers1

19

The migration guide's code examples cover that. You should use UseKestrel on the builder's WebHost:

builder.WebHost.UseKestrel(so =>
{
    so.Limits.MaxConcurrentConnections = 100;
    so.Limits.MaxConcurrentUpgradedConnections = 100;
    so.Limits.MaxRequestBodySize = 52428800;
});
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • 2
    That took me way too long to figure out `builder.WebHost.UseSentry();` lol thank you! I was also trying to use `builder.Host.ConfigureWebHostDefaults(builder => { });` – Thomas Dec 11 '21 at 22:54
  • 1
    Beware that if you use this and end up hosting in IIS this will blow up on startup. Sucks because in dev you're probably running Kestrel and won't catch it until it fails on IIS when deployed. – Rick Strahl May 08 '23 at 16:10
  • This doesn't work, it just skips right past the function call – Aquaphor Jul 24 '23 at 22:09
  • @Aquaphor can you please explain what exactly does not work, were it does skip and provide a [mre]? – Guru Stron Jul 24 '23 at 22:16
  • @GuruStron I made a post for my issue: https://stackoverflow.com/questions/76758764/c-sharp-app-run-is-failing-because-usekestrel-is-not-waiting-for-the-default – Aquaphor Jul 25 '23 at 00:28