IServerAddressesFeature addresses empty when running under dotnet.exe

笑着哭i 提交于 2020-04-13 04:58:10

问题


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?


回答1:


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 the IServerAddressesFeature 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
}



回答2:


When no url is specified the server does not choose a default until after Startup. If you're the app deployer then make sure to specify a non default url when starting the app.

Note for the IIS/Express case you're getting the private address used by the reverse proxy. There's no way to get the public address in process.



来源:https://stackoverflow.com/questions/48546843/iserveraddressesfeature-addresses-empty-when-running-under-dotnet-exe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!