kestrel修改服务器名,如何修改 .NET Core Kestrel 下的端口

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

实现方法

ASPNETCORE_URLS 环境变量

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

CODE1set ASPNETCORE_URLS=http://127.0.0.1:5008;http://0.0.0.0:5009

RESULT

35f975aeba739760ede9124a4deae4c1.png

–urls 命令行参数

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

CODE1set dotnet EndpointConfigurationTest2.0.dll --urls http://0.0.0.0:5698;https://127.0.0.1:6936

RESULT

773584ff6eb4ff070951990f34cd1530.png

UseUrls

使用 IWebHostBuilder 的扩展方法 UseUrls() 可以为 Kestrel 绑定一个或者多个 url ,支持 http 与 https,支持多个 string 参数或者单个 string 中使用分号分割。

CODE1

2

3

4public 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();

RESULT

43b6e261109892f63f2080f29e456e46.png

配置文件

在配置文件中增加 Kestrel 节点来配置 Kestrel 使用的端口

CODE1

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

02aa5e1cc3949dc485b2f4665009f7ea.png

UseKestrel 或者 ConfigureKestrel

使用 IWebHostBuilder 的扩展方法 UseKestrel() 可以更精确的设置 Kestrel 的更多配置信息 ,在 .NET Core 2.1 版本以上也可以为 ConfigureKestrel()。

CODE1

2

3

4

5

6

7

8

9

10

11

12public 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()

.UseKestrel((context, options) =>

{

options.Listen(IPAddress.Any, 5620);

options.Listen(IPAddress.Loopback, 5588, listenOptions =>

{

listenOptions.UseHttps();

});

});

RESULT

d18d958dbf1a0a3fe80437e7f57c213c.png

总结

以上几种方法就是我根据官方文档整理的修改 Kestrel 端口的方法,实测优先级由上到下依次增高,使用优先级更高的方式可以覆盖掉优先级低的方式。

综上,需要测试 Consul 服务治理时,更合适的方式是使用命令行 –urls 方式.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值