Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 916
Christo Avatar asked Sep 19 '17 07:09

Christo


People also ask

What port does .NET run on?

ASP.NET Core projects are configured to bind to a random HTTP port between 5000-5300 and a random HTTPS port between 7000-7300. This default configuration is specified in the generated Properties/launchSettings.

How do I change the port in .NET core?

To change the port the application is using, Open the file lunchSetting. json. You will find it under the properties folder in your project and as shown below. Inside the file, change applicationUrl port (below is set to 5000) to a different port number and save the file.

How do I change the port on my Kestrel?

You can set the Kestrel ports inside the appsettings. json file. A simple block of JSON does it. You might notice that there is an appsettings.Development.

What is Usekestrel?

Kestrel is a cross-platform web server for ASP.NET Core based on libuv, a cross-platform asynchronous I/O library. Kestrel is the web server that is included by default in ASP.NET Core project templates. You can use Kestrel by itself or with a reverse proxy server, such as IIS, Nginx, or Apache.


1 Answers

You can use the Start() method instead of Run() to access IServerAddressesFeature at the right moment:

IWebHost webHost = new WebHostBuilder()
    .UseKestrel(options => 
         options.Listen(IPAddress.Loopback, 0)) // dynamic port
    .Build();

webHost.Start();

string address = webHost.ServerFeatures
    .Get<IServerAddressesFeature>()
    .Addresses
    .First();
int port = int.Parse(address.Split(':').Last());

webHost.WaitForShutdown();
like image 124
Vladimir Panchenko Avatar answered Sep 20 '22 16:09

Vladimir Panchenko