I've got an ASP.NET Core 2.0 app which I intend to run as a stand-alone application. The app should start up and bind to an available port. To achieve this I configure the WebHostBuilder to listen on "http://127.0.0.1:0" and to use the Kestrel server. Once the web host starts listening I want to save the url with the actual port in a file. I want to do this as early as possible, since another application will read the file to interact with my app.
How can I determine the port the web host is listening on?
I'm able to do it using reflection (ugh!). I've registered an
IHostedService
and injectedIServer
. TheListenOptions
property onKestrelServerOptions
is internal, therefore I need to get to it using reflection. When the hosted service is called I then extract the port using the following code: