如何修改 .NET Core Kestrel 下的端口
今天在尝试 Consul 的时候需要动态改变 .NET Core Kestrel 下的端口以方便测试,故而查了查,发现原来除了最常使用的 UseUrls 之外,还有许多其他方法,故而总结一下。
实现方法
ASPNETCORE_URLS 环境变量
使用环境变量可以配置 Kestrel 使用的端口
CODE
set ASPNETCORE_URLS=http://127.0.0.1:5008;http://0.0.0.0:5009
RESULT
–urls 命令行参数
使用 –urls 命令行参数可以配置 Kestrel 使用的端口
CODE
set dotnet EndpointConfigurationTest2.0.dll --urls http://0.0.0.0:5698;https://127.0.0.1:6936
RESULT
UseUrls
使用 IWebHostBuilder 的扩展方法 UseUrls () 可以为 Kestrel 绑定一个或者多个 url ,支持 http 与 https,支持多个 string 参数或者单个 string 中使用分号分割。
CODE
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseUrls("http://localhost:4411","https://localhost:4412","http://0.0.0.0:4413;https://localhost:4414")
.UseStartup<Startup>();
RESULT
配置文件
在配置文件中增加 Kestrel 节点来配置 Kestrel 使用的端口
CODE
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"Kestrel": {
"EndPoints": {
"Http": {
"Url": "http://localhost:5000"
},
"Https": {
"Url": "https://localhost:5006"
}
}
}
}
RESULT
UseKestrel 或者 ConfigureKestrel
使用 IWebHostBuilder 的扩展方法 UseKestrel () 可以更精确的设置 Kestrel 的更多配置信息 ,在 .NET Core 2.1 版本以上也可以为 ConfigureKestrel ()。
CODE
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseUrls("http://localhost:4411","https://localhost:4412","http://0.0.0.0:4413;https://localhost:4414")
.UseStartup<Startup>()
.UseKestrel((context, options) =>
{
options.Listen(IPAddress.Any, 5620);
options.Listen(IPAddress.Loopback, 5588, listenOptions =>
{
listenOptions.UseHttps();
});
});
RESULT
总结
以上几种方法就是我根据官方文档整理的修改 Kestrel 端口的方法,实测优先级由上到下依次增高,使用优先级更高的方式可以覆盖掉优先级低的方式。
综上,需要测试 Consul 服务治理时,更合适的方式是使用命令行 –urls 方式.
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器
· 面试官:你是如何进行SQL调优的?