gpt4 book ai didi

asp.net-core - 确定 Kestrel 绑定(bind)的端口

转载 作者:行者123 更新时间:2023-12-02 02:12:57 25 4
gpt4 key购买 nike

我正在使用 ASP.NET Core 空 (web) 模板编写一个简单的 ASP.NET Core 服务。

默认情况下,它绑定(bind)到端口 5000,但我希望它绑定(bind)到系统上的随机可用端口。

我可以通过将 BuildWebHost 修改为:

    public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseUrls("http://*:0") // This enables binding to random port
.Build();

它绑定(bind)到随机端口,但我如何从应用程序内确定我正在监听哪个端口?

最佳答案

可以通过 IServerAddressesFeature.Addresses 集合访问 ASP.NET Core 应用程序的托管地址。

主要的挑战是在正确的时间调用代码来分析这个集合。实际的端口绑定(bind)在调用 IWebHost.Run() 时发生(来自 Program.Main())。因此,您还无法在 Startup.Configure() 方法中访问托管地址,因为此阶段尚未分配端口。并且在调用 IWebHost.Run() 后您会失去控制,因为此调用在 Web 主机关闭之前不会返回。

据我了解,分析绑定(bind)端口最合适的方法是通过执行 IHostedService 。这是工作示例:

public class GetBindingHostedService : IHostedService
{
public static IServerAddressesFeature ServerAddresses { get; set; }

public Task StartAsync(CancellationToken cancellationToken)
{
var address = ServerAddresses.Addresses.Single();
var match = Regex.Match(address, @"^.+:(\d+)$");
if (match.Success)
{
int port = Int32.Parse(match.Groups[1].Value);
Console.WriteLine($"Bound port is {port}");
}

return Task.CompletedTask;
}

public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}

Startup类中:

public class Startup
{

// ...

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSingleton<IHostedService, GetBindingHostedService>();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseMvc();

GetBindingHostedService.ServerAddresses = app.ServerFeatures.Get<IServerAddressesFeature>();
}
}

IServerAddressesFeature 的实例通过 GetBindingHostedService 中丑陋的静态属性传递。我看不出有其他方法可以将其注入(inject)到服务中。

Sample Project on GitHub

总的来说,我对这样的解决方案并不满意。它完成了这项工作,但看起来比应有的要复杂得多。

关于asp.net-core - 确定 Kestrel 绑定(bind)的端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49871318/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com