我有一个 ASP.NET Core 2.0 Web 应用程序,我需要在启动期间传递应用程序的 URL,以便集成到其他应用程序中。
在 Visual Studio (IIS Express) 下运行时,
IApplicationBuilder.ServerFeatures.Get<IServerAddressesFeature>().Addresses
包含我的应用程序绑定到的 URL(例如 http://localhost:1234
)。
当使用
dotnet.exe myapp.dll
运行时,同一个集合是空的,但是,我在标准输出上看到一行内容为 Now listening on: http://localhost:5000
。
问题是,要获取 URL,我是否必须解析 dotnet.exe 的输出以获取以
Now listening on:
开头的行,或者是否有一种不那么脆弱的方法?
这是由于 2017 年 3 月对 Kestrel 进行的更改所致。来自 公告:
未显式配置地址时,Hosting 不再添加默认服务器地址
当未指定时,WebHost 将不再将默认服务器地址
添加到http://localhost:5000
。默认服务器地址的配置现在将由服务器负责。IServerAddressesFeature
中指定的地址旨在供服务器在未直接指定显式地址时用作后备。IServerAddressesFeature
在没有显式配置地址时,Hosting 不再添加默认服务器地址中有一个如何处理此问题的示例:
如果您正在实现服务器并依靠托管来设置
,则将不再设置该值,并且在未配置地址时应添加默认值。举个例子:IServerAddressesFeature
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 }
如果未指定 url,服务器在启动后才会选择默认值。如果您是应用程序部署者,请确保在启动应用程序时指定非默认 URL。
注意对于 IIS/Express 情况,您将获得反向代理使用的私有地址。无法获取正在处理的公共地址。
Kestrel 的工作解决方案可以在这里找到: https://nodogmablog.bryanhogan.net/2022/01/programmatically-define-what-ports-kestrel-is-running-on/
这个想法是在服务器初始化后获取地址,正如@Tratcher在他的answer中所建议的那样。这是一个工作代码示例:
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Builder;
WebApplication app = WebApplication.CreateBuilder().Build();
//app.Run(); // This starts the server and waits indefinitely. Not helpful.
app.Start(); // Start and wait for the server to be ready.
var server = app.Services.GetService<IServer>();
var addressFeature = server.Features.Get<IServerAddressesFeature>();
foreach (var address in addressFeature.Addresses)
{
Console.WriteLine("Kestrel is listening on address: " + address);
}
await app.StopAsync(); // Shutdown the server.
//app.WaitForShutdown(); // Use this in production to wait indefinitely.
显示:
Kestrel is listening on address: http://localhost:5073