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

时间:2017-09-19 07:51:20

标签: kestrel-http-server asp.net-core-2.0

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

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

5 个答案:

答案 0 :(得分: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));
}

答案 1 :(得分:4)

您可以在适当的时候使用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(':')[1]);

Console.ReadKey();

答案 2 :(得分:1)

我能用反射做到这一点(唉!)。我已注册了IHostedService并注入IServerListenOptions上的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;

答案 3 :(得分:1)

我能够使用以下代码在StartUp.cs中进行操作:

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

答案 4 :(得分:0)

至少从.Net Core 3中,您可以注入IServer并获取信息。

using System;
using System.Linq;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;

namespace MyApp.Controllers
{
    public class ServerInfoController : Controller
    {
        public ServerInfoController (IServer server)
        {
            var addresses = server.Features.Get<IServerAddressesFeature>()?.Addresses?.ToArray();
        }
    }
}