1234567891011121314151617181920212223242526272829303132333435363738 |
- using System.Net;
- using Microsoft.AspNetCore.Hosting.Server;
- public class PocKestrelAutoPort
- {
- public static async Task RunPoc()
- {
- var host = Host.CreateDefaultBuilder()
- .ConfigureWebHostDefaults(webBuilder =>
- {
- webBuilder.ConfigureKestrel(serverOptions =>
- {
- serverOptions.Listen(IPAddress.Parse("127.0.0.1"), 0); // 使用端口 0,让系统自动分配端口
- });
- webBuilder.Configure(app =>
- {
- app.Run(async context =>
- {
- await context.Response.WriteAsync("Hello, world!");
- });
- });
- })
- .Build();
- // 启动后获取实际端口
- host.Start();
- var addressFeature = host.Services.GetRequiredService<IServer>().Features
- .Get<Microsoft.AspNetCore.Hosting.Server.Features.IServerAddressesFeature>();
- var boundAddress = addressFeature.Addresses.FirstOrDefault();
- System.Console.WriteLine($"Server bound to: {boundAddress}");
- await host.WaitForShutdownAsync();
- }
- }
|