A working sample from .NET Core 6:
In your Program.cs, you will have the following (with more or less embellishment, depending on the middleware):
var builder = WebApplication.CreateBuilder(args);
/* ... kestrel configuration, middleware setup ... */
var app = builder.Build();
app.Services.GetService<IHostApplicationLifetime>()!.ApplicationStarted.Register(() =>
{
/* any code you put here will execute
* after the host has started listening */
Console.WriteLine("Kestrel has started listening");
});
/* this is a blocking call.
* the start event occurs from "in there" */
app.Run();
Working principle: The event handler with the Console.WriteLine
call will be called after app.Run()
is already blocking the main thread, at the exact moment when the server is first ready and will accept requests.