【问题标题】:Kestrel Port:0, how to detect autoselected portKestrel Port:0,如何检测自动选择的端口
【发布时间】:2020-10-28 06:13:51
【问题描述】:

我希望 Kestrel 自动选择一个端口。我的 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 以了解如何检测所选端口。但其实我想在软件启动时获取端口。

我尝试了以下方法:

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

【问题讨论】:

    标签: c# asp.net-core kestrel-http-server


    【解决方案1】:

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

    应用程序启动时,会先调用startup.cs的configure方法。这次 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);
                }
            }
        }
    

    结果:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-02
      • 2013-11-03
      • 1970-01-01
      • 2011-07-17
      • 2012-01-08
      相关资源
      最近更新 更多