How to determine which port ASP.NET Core 2 is listening on when a dynamic port (0) was specified

孤街醉人 提交于 2019-12-12 08:38:46

问题


I've got an ASP.NET Core 2.0 app which I intend to run as a stand-alone application. The app should start up and bind to an available port. To achieve this I configure the WebHostBuilder to listen on "http://127.0.0.1:0" and to use the Kestrel server. Once the web host starts listening I want to save the url with the actual port in a file. I want to do this as early as possible, since another application will read the file to interact with my app.

How can I determine the port the web host is listening on?


回答1:


You can achive it in Startup class in method Configure. You can get port from ServerAddressesFeature

Here is an example of code:

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));
}



回答2:


You can use the Start() method instead of Run() to access IServerAddressesFeature at the right moment:

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();



回答3:


I'm able to do it using reflection (ugh!). I've registered an IHostedService and injected IServer. The ListenOptions property on KestrelServerOptions is internal, therefore I need to get to it using reflection. When the hosted service is called I then extract the port using the following code:

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;



回答4:


I was able to do it in the StartUp.cs using the following code:

int Url = new System.Uri(Configuration["urls"]).Port;


来源:https://stackoverflow.com/questions/46294883/how-to-determine-which-port-asp-net-core-2-is-listening-on-when-a-dynamic-port

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!