如何修改 .NET Core Kestrel 下的端口

今天在尝试 Consul 的时候需要动态改变 .NET Core Kestrel 下的端口以方便测试,故而查了查,发现原来除了最常使用的 UseUrls 之外,还有许多其他方法,故而总结一下。

实现方法

ASPNETCORE_URLS 环境变量

使用环境变量可以配置 Kestrel 使用的端口
CODE

1
set ASPNETCORE_URLS=http://127.0.0.1:5008;http://0.0.0.0:5009
 

RESULT

–urls 命令行参数

使用 –urls 命令行参数可以配置 Kestrel 使用的端口
CODE

1
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

1
2
3
4
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
"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

1
2
3
4
5
6
7
8
9
10
11
12
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 方式.

 

转 https://wayneshao.com/posts/15088.html

posted @   dreamw  阅读(401)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示