Determine port Kestrel binded to

后端 未结 2 894
感动是毒
感动是毒 2020-12-19 08:30

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

2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-19 09:03

    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();
        }
    

提交回复
热议问题