背景
".NET 6"中的"托管"机制已经改变。之前,IWebHost
拥有IWebHost.ServerFeatures
属性,该属性可用于获取IServerAddressFeature
,例如(来自此SO答案):
IWebHost host = new WebHostBuilder()
.UseStartup<Startup>()
.UseUrls("http://*:0") // This enables binding to random port
.Build();
host.Start();
foreach(var address in host.ServerFeatures.Get<IServerAddressesFeature>().Addresses) {
var uri = new Uri(address);
var port = uri.Port;
Console.WriteLine($"Bound to port: {port}");
}
问题:如何在.NET 6中使用IHost获取端口号?
现在我有一个IHost
,如何获取端口号(在???
处):
public class Program {
public static void Main(string[] args) {
IHostBuilder hostBuilder = Host.CreateDefaultBuilder(args);
hostBuilder.ConfigureWebHostDefaults(webHostBuilder => {
webHostBuilder.ConfigureKestrel(opts => {
opts.ListenAnyIP(0); // bind web server to random free port
});
webHostBuilder.UseStartup<Startup>();
});
IHost host = hostBuilder.Build();
host.Start();
// If it doesn't fail, at this point Kestrel has started
// and is listening on a port. It even prints the port to
// console via logger.
int boundPort = ???; // some magic GetPort(IHost host) method
// This link in the docs mentions getting the port, but the example
// they provide is incomplete
// https://learn.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel/endpoints?view=aspnetcore-6.0#port-0
host.WaitForShutdown();
}
}
来自Microsoft文档的示例:
当指定端口号为0时,Kestrel会动态绑定到一个可用端口。以下示例显示如何在运行时确定Kestrel绑定的端口号:
app.Run(async (context) =>
{
var serverAddressFeature = context.Features.Get<IServerAddressesFeature>();
if (serverAddressFeature is not null)
{
var listenAddresses = string.Join(", ", serverAddressFeature.Addresses);
// ...
}
});
在这个例子中,什么是
app
?我在哪里可以获得那个带有.Features
的context
?