如何获取 ASP.NET Core 当前启动地址?

前言

上次,我们介绍了配置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获取:

/// <summary>
/// The list of URLs that the HTTP server is bound to.
/// </summary>
public ICollection<string> Urls => ServerFeatures.GetRequiredFeature<IServerAddressesFeature>().Addresses;

internal IFeatureCollection ServerFeatures => _host.Services.GetRequiredService<IServer>().Features;

更重要的是,该接口支持所有 ASP.NET Core 版本:

如何获取 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<IServerAddressesFeature>().Addresses.First());

    await host.WaitForShutdownAsync();
}

结论

获取 ASP.NET Core 启动地址在某些场景下非常有用,比如服务注册。