前言
上次,我们介绍了配置ASP.NET Core启动地址的多种方法。
那么,如何通过代码方式,获取启动后的地址?
WebApplication.Urls 对象使用 WebApplication.Urls.Add 方法可以添加启动地址。
那么,使用 WebApplication.Urls 应该可以获取启动地址。
那如何在启动完成后能够访问 WebApplication.Urls 呢?
我们可以不用Run
方法启动,而是等待Start
完成:
await app.StartAsync();
Console.WriteLine(app.Urls.First());
await app.WaitForShutdownAsync();
但是,这是 .NET 6 的实现方式, .NET 5 没有这个对象。
IServerAddressesFeature查看 WebApplication.Urls 的源码,发现它实际调用的是IServerAddressesFeature
提供的属性,而该实例可以通过IServer
获取:
///
/// The list of URLs that the HTTP server is bound to.
///
public ICollection Urls => ServerFeatures.GetRequiredFeature().Addresses;
internal IFeatureCollection ServerFeatures => _host.Services.GetRequiredService().Features;
更重要的是,该接口支持所有 ASP.NET Core 版本:
因此,最后的实现代码如下:
public static async Task Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
await host.StartAsync();
var server = host.Services.GetService(typeof(IServer)) as IServer;
Console.WriteLine(server.Features.Get().Addresses.First());
await host.WaitForShutdownAsync();
}
结论
获取 ASP.NET Core 启动地址在某些场景下非常有用,比如服务注册。