How to determine which port ASP.NET Core 2 is listening on when a dynamic port (0) was specified

Christo picture Christo · Sep 19, 2017 · Viewed 8.5k times · Source

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?

Answer

Oleg Lukash picture Oleg Lukash · Nov 26, 2017

You can achive it in Startup class in method Configure. You can get port from ServerAddressesFeature

Here is an example of code:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ILogger<Startup> logger)
{
     var serverAddressesFeature = app.ServerFeatures.Get<IServerAddressesFeature>();

     loggerFactory.AddFile("logs/myfile-{Date}.txt", minimumLevel: LogLevel.Information, isJson: false);

     logger.LogInformation("Listening on the following addresses: " + string.Join(", ", serverAddressesFeature.Addresses));
}