I\'m writing a simple ASP.NET Core service using ASP.NET Core empty (web) template.
By default, it binds to port 5000 but I would like it to bind to a r
You can call IWebHost.Start() instead of IWebHost.Run() as suggested here. This will allow execution of your Main method to continue so you can get the desired information from IWebHost.ServerFeatures. Just remember, your application will shutdown immediately unless you explicitly tell it not to using IWebHost.WaitForShutdown().
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseStartup()
.UseUrls("http://*:0") // This enables binding to random port
.Build();
host.Start();
foreach(var address in host.ServerFeatures.Get().Addresses)
{
var uri = new Uri(address);
var port = uri.Port;
Console.WriteLine($"Bound to port: {port}");
}
//Tell the host to block the thread just as host.Run() would have.
host.WaitForShutdown();
}