Configuring Kestrel Server Options in .NET 6 Startup
Asked Answered
A

1

15

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.

Ammoniac answered 9/11, 2021 at 19:52 Comment(0)
M
21

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;
});
Minorite answered 9/11, 2021 at 20:10 Comment(5)
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 => { });Wapiti
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.Precondition
This doesn't work, it just skips right past the function callPassementerie
@Passementerie can you please explain what exactly does not work, were it does skip and provide a minimal reproducible example?Minorite
@GuruStron I made a post for my issue: #76759264Passementerie

© 2022 - 2024 — McMap. All rights reserved.