如何在指定动态端口(0)时确定ASP.NET Core 2正在侦听哪个端口

Chr*_*sto 7 kestrel-http-server asp.net-core-2.0

我有一个ASP.NET Core 2.0应用程序,我打算作为一个独立的应用程序运行.应用程序应启动并绑定到可用端口.为此,我将WebHostBuilder配置为侦听" http://127.0.0.1:0 "并使用Kestrel服务器.一旦web主机开始监听,我想用文件中的实际端口保存url.我想尽早做到这一点,因为另一个应用程序将读取文件以与我的应用程序进行交互.

如何确定Web主机正在侦听的端口?

小智 8

您可以在方法Configure中的Startup类中实现它.您可以从ServerAddressesFeature获取端口

这是一个代码示例:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ILogger<Startup> logger)
{
     var serverAddressesFeature = app.ServerFeatures.Get<IServerAddressesFeature>();

     loggerFactory.AddFile("logs/myfile-{Date}.txt", minimumLevel: LogLevel.Information, isJson: false);

     logger.LogInformation("Listening on the following addresses: " + string.Join(", ", serverAddressesFeature.Addresses));
}
Run Code Online (Sandbox Code Playgroud)

  • 有0个地址,任何想法为什么? (4认同)

Vla*_*nko 5

您可以使用该Start()方法而不是在适当的时候Run()进行访问IServerAddressesFeature

IWebHost webHost = new WebHostBuilder()
    .UseKestrel(options => 
         options.Listen(IPAddress.Loopback, 0)) // dynamic port
    .Build();

webHost.Start();

string address = webHost.ServerFeatures
    .Get<IServerAddressesFeature>()
    .Addresses
    .First();
int port = int.Parse(address.Split(':').Last());

webHost.WaitForShutdown();
Run Code Online (Sandbox Code Playgroud)


Chr*_*sto 2

我可以使用反射来做到这一点(呃!)。我已经注册IHostedService并注入了IServer. ListenOptionson 的属性是KestrelServerOptions内部的,因此我需要使用反射来获取它。当调用托管服务时,我使用以下代码提取端口:

var options = ((KestrelServer)server).Options;
var propertyInfo = options.GetType().GetProperty("ListenOptions", BindingFlags.Instance | BindingFlags.NonPublic);
var listenOptions = (List<ListenOptions>)propertyInfo.GetValue(options);
var ipEndPoint = listenOptions.First().IPEndPoint;
var port = ipEndPoint.Port;
Run Code Online (Sandbox Code Playgroud)