I have a ASP.NET Core 2.0 web application, where I need to pass the application's URL out during startup for the purposes of integration into something else.
When running under Visual Studio (IIS Express), IApplicationBuilder.ServerFeatures.Get<IServerAddressesFeature>().Addresses
contains the URL my application is bound to (e.g. http://localhost:1234
).
When run using dotnet.exe myapp.dll
, the same collection is empty, however, I get a line on stdout saying Now listening on: http://localhost:5000
.
The question is, to get the URL, do I have to parse the output of dotnet.exe for the line beginning Now listening on:
, or is there a less fragile way?
This is due to a change made to Kestrel in March 2017. From the announcement:
Hosting no longer adds default server address when no address is explicitly configured
The WebHost will no longer add the default server address of
http://localhost:5000
to theIServerAddressesFeature
when none is specified. The configuration of the default server address will now be a responsibility of the server.Addresses specified in
IServerAddressesFeature
are intended to be used by servers as a fallback when no explicit address is specified directly.
There is an example of how to handle this in Hosting no longer adds default server address when no address is explicitly configured:
If you are implementing a server and rely on the
IServerAddressesFeature
to be set by hosting, that will no longer be set and a default should be added when no address is configured. As an example:var serverFeatures = featureCollection.Get<IServerAddressesFeature>(); if (serverFeatures .Addresses.Count == 0) { ListenOn(DefaultAddress); // Start the server on the default address serverFeatures.Addresses.Add(DefaultAddress) // Add the default address to the IServerAddressesFeature }
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