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
I'm able to do it using reflection (ugh!). I've registered an IHostedService and injected IServer. The ListenOptions property on KestrelServerOptions 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:
var options = ((KestrelServer)server).Options;
var propertyInfo = options.GetType().GetProperty("ListenOptions", BindingFlags.Instance | BindingFlags.NonPublic);
var listenOptions = (List)propertyInfo.GetValue(options);
var ipEndPoint = listenOptions.First().IPEndPoint;
var port = ipEndPoint.Port;