Kestrel Port:0,如何检测自动选择的端口

Kestrel Port:0, how to detect autoselected port

我希望 Kestrel 自动 select 一个端口。我的 Program.cs 看起来像这样:

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                var builder = webBuilder.UseStartup<Startup>();
                if (args.Contains("--automatic-port-selection"))
                {
                    builder.UseUrls("http://127.0.0.1:0");
                }
            });

我查看了 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel?view=aspnetcore-3.1 以了解如何检测 selected 端口。但是我其实是想在软件启动的时候获取端口

我尝试了以下方法:

public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services) { }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        var serverAddressesFeature =
            app.ServerFeatures.Get<IServerAddressesFeature>();


        if (serverAddressesFeature != null)
        {
            foreach (var address in serverAddressesFeature.Addresses)
            {
                int port = int.Parse(address.Split(':').Last());
                Console.Out.WriteLine("Port:" + port);
            }

            Console.Out.Flush();
        }

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();

        app.UseEndpoints(endpoints => { endpoints.MapGet("/", async context => { await context.Response.WriteAsync("Hello World!"); }); });
    }
}

您可以看到这基本上只是一个从 Visual Studio 模板创建的 aspnet 核心应用程序。

这里的问题是它总是只写0。似乎只有当我读serverAddressesFeature时它才能给出正确的端口号。处理请求时的地址。如何获取服务器启动时使用的端口号?

编辑

这似乎是相关的:https://github.com/aspnet/Hosting/issues/1390

据我所知,你总是得到0端口号的原因是应用程序没有完全启动。

应用启动时,会先调用startup.cs配置方法。这次Kestrel知道它的端口是0.

之后它将找到自动空闲端口。

因此,如果您想获取您的应用程序现在正在使用的端口。您可以编写一个方法,该方法将在应用程序完全声明以记录正确的端口后触发。

更多详情,您可以参考以下代码:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifetime , IServiceProvider serviceProvider){

   //other codes ....

               lifetime.ApplicationStarted.Register(
  () => LogAddresses(app.ServerFeatures));
}

    static void LogAddresses(IFeatureCollection features)
    {
        var addressFeature = features.Get<IServerAddressesFeature>();
        if (addressFeature != null)
        {
            foreach (var address in addressFeature.Addresses)
            {
                int port = int.Parse(address.Split(':').Last());
                Console.Out.WriteLine("Port:" + port);
            }
        }
    }

结果: