【发布时间】: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 时,它似乎只能给出正确的端口号。处理请求时的地址。启动服务器时如何获取使用的端口号?
编辑
【问题讨论】:
标签: c# asp.net-core kestrel-http-server