前言
上次,我們讨論了如何通過配置或代碼方式修改啟動位址:《ASP.NET Core啟動位址配置方法及優先級順序》。不過是基于 .NET 5 版本的。
由于 .NET 6 使用了最小 WEB API, 配置方式已經部分發生了變化。
設定方法
1. applicationUrl 屬性
launchSettings.json 檔案中的 applicationUrl 屬性,但是僅在本地開發計算機上使用:
"profiles": {
"WebApplication1": {
...
"applicationUrl": "http://localhost:5100",
}
}
2.環境變量
環境變量 ASPNETCORE_URLS,有多個設定位置,下面示範的是使用 launchSettings.json 檔案:
"profiles": {
"WebApplication1": {
...
"environmentVariables": {
"ASPNETCORE_URLS": "http://localhost:5200"
}
}
}
3.指令行參數
指令行參數 --urls,有多個設定位置,下面示範的是使用 launchSettings.json 檔案:
"profiles": {
"WebApplication1": {
...
"commandLineArgs": "--urls http://localhost:5300",
}
}
4. UseUrls 方法
.NET 5 版本
修改 ConfigureWebHostDefaults 方法:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.UseUrls("http://localhost:5400");
});
.NET 6 版本
對應的方法為 WebApplicationBuilder.WebHost.UseUrls:
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.UseUrls("http://localhost:5400");
但是,運作後不起作用。
結果發現這是 .NET 6 的 BUG (Builder.WebHost.UseUrls does not seem to override default url),并将在 6.0.3 中修複:https://github.com/dotnet/aspnetcore/issues/38185
5. UseKestrel 方法
修改ConfigureWebHostDefaults方法:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.UseKestrel(options=> options.ListenLocalhost(5500, opts => opts.Protocols = HttpProtocols.Http1));
});
對應的方法為 WebApplicationBuilder.WebHost.ConfigureKestrel:
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(options => options.ListenLocalhost(5500, opts => opts.Protocols = HttpProtocols.Http1));
6. WebApplication.Urls.Add 方法
這是 .NET 6 下增加的新方法:
var app = builder.Build();
app.Urls.Add("http://localhost:5600");
7. appsettings.json 檔案
可以在 appsettings.json 檔案中設定 Kestrel 端口:
{
"Kestrel": {
"Endpoints": {
"Https": {
"Url": "https://*:5701"
},
"Http": {
"Url": "http://*:5700"
}
}
}
}
優先級
通過将上述設定方式進行組合,發現優先級順序如下:
- WebApplicationBuilder.WebHost.ConfigureKestrel 方法 / appsettings.json 檔案 (2者可同時起作用)
- WebApplication.Urls.Add 方法
- 指令行參數 --urls
- 環境變量 ASPNETCORE_URLS
- applicationUrl 屬性
- 預設值
結論
如果在同一台機器上運作多個 ASP.NET Core 執行個體,使用預設值肯定不合适。
由于 WebApplicationBuilder.WebHost.ConfigureKestrel/WebApplication.Urls.Add 方法不能被覆寫,而環境變量 ASPNETCORE_URLS 容易造成全局影響。
建議:始終使用 appsettings.json 檔案配置啟動位址。