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?
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.
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.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With