.net core運行的默認端口是5000,可是不少時候咱們須要自定義端口。有兩種方式html
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
設置端口的一個封裝而已,源碼linux
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)); }
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也能夠作到,源碼:web
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
)export ASPNETCORE_URLS="http://*:5001"
set ASPNETCORE_URLS="http://*:5001"
dotnet xxx.dll
環境變量的方法爲什麼能實現?在WebHostBuilder
的構造函數中存在着這麼一句:json
_config = new ConfigurationBuilder() .AddEnvironmentVariables(prefix: "ASPNETCORE_") .Build();
前兩種方法都是會變成UseSetting
,而UseSetting
的實現也很簡單windows
public IWebHostBuilder UseSetting(string key, string value) { _config[key] = value; return this; }
只是設置了個key,value。環境變量方法最後也是設置個key,value。
那麼,那種方法比較好呢?我的認爲環境變量方法好一點,靈活,不用在代碼裏面多寫一句代碼。app
注意: 在上面中設置端口的http://*:xxx
中,*
別改爲localhost
或者ip,由於這樣要麼外網訪問不了要麼內網訪問不了,至關蛋疼,寫*
改變環境也不用改,多爽!函數