.net core運行的默認端口是5000,但是很多時候我們需要自定義端口。有兩種方式
寫在Program
的Main
方法里面
添加 .UseUrls()
var host = new WebHostBuilder()
.UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory())
//添加這一行
.UseUrls("http://*:5001", "http://*:5002")
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
添加 .UseSetting()
var host = new WebHostBuilder()
.UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory())
//添加這一行
.UseSetting(WebHostDefaults.ServerUrlsKey, "http://*:5001;http://*5002")
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
小結
UseUrls
是UseSetting
設置端口的一個封裝而已,源碼
public static IWebHostBuilder UseUrls(this IWebHostBuilder hostBuilder, params string[] urls)
{
if (urls == null)
{
throw new ArgumentNullException(nameof(urls));
}
return hostBuilder.UseSetting(WebHostDefaults.ServerUrlsKey, string.Join(ServerUrlsSeparator, urls));
}
寫在配置文件中
- 在項目中新建一個.json文件,例如
config/hosting.json
.內容:
{
"urls": "http://*:5003;http://*:5004"
}
Main
方法添加配置
// using Microsoft.Extensions.Configuration;
public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
// 這里添加配置文件
.AddJsonFile(Path.Combine("config", "hosting.json"), true)
.Build();
var host = new WebHostBuilder()
.UseKestrel()
// 添加配置
.UseConfiguration(config)
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
- 最后別忘了在
project.json
中添加輸出配置:(像我就直接把整個config目錄放進去了)
"publishOptions": {
"include": [
"wwwroot",
"**/*.cshtml",
"appsettings.json",
"web.config",
"config"
]
},
小結
其實這種方法最終也是變成UseSetting
,用appsetting.json也可以做到,源碼:
public static IWebHostBuilder UseConfiguration(this IWebHostBuilder hostBuilder, IConfiguration configuration)
{
foreach (var setting in configuration.AsEnumerable())
{
hostBuilder.UseSetting(setting.Key, setting.Value);
}
return hostBuilder;
}
用環境變量
- 環境變量的名字
ASPNETCORE_URLS
(過時的名字是:ASPNETCORE_SERVER.URLS
) - 設置臨時環境變量
- linux:
export ASPNETCORE_URLS="http://*:5001"
- windows:
set ASPNETCORE_URLS="http://*:5001"
- linux:
- 設置完之后運行即可
dotnet xxx.dll
小結
環境變量的方法為何能實現?在WebHostBuilder
的構造函數中存在着這么一句:
_config = new ConfigurationBuilder()
.AddEnvironmentVariables(prefix: "ASPNETCORE_")
.Build();
總結
前兩種方法都是會變成UseSetting
,而UseSetting
的實現也很簡單
public IWebHostBuilder UseSetting(string key, string value)
{
_config[key] = value;
return this;
}
只是設置了個key,value。環境變量方法最后也是設置個key,value。
那么,那種方法比較好呢?個人認為環境變量方法好一點,靈活,不用在代碼里面多寫一句代碼。
注意: 在上面中設置端口的http://*:xxx
中,*
別改成localhost
或者ip,因為這樣要么外網訪問不了要么內網訪問不了,相當蛋疼,寫*
改變環境也不用改,多爽!