今天無心中發現一個變化,由於好久沒看.net core的項目了,發現項目啓動的默認端口已經不是5000了,記得很清楚,最先那仍是.net core 1.x版本的時候,每次啓動都會默認是5000端口號,而如今不是了。藉此機會在來講一下,關於.net core項目修改默認端口號的解決方案,咱們最熟知的是一種解決方案就是直接在Program.cs中建立WebHost對象的時候,使用UseUrls()方法,配置要使用的端口,以下所示:git
這是咱們再熟悉不過的修改方法了,啓動之後,5001和5002端口都會開啓監聽,因此咱們經過這兩個地址都會訪問到咱們的網站。可是這種方式的缺點就是咱們要修改代碼,從新編譯運行,這並非咱們想要的最好的解決方案,若是能夠直接在配置文件中配置就完美了,便在一個我的博客裏看到了一個方法,地址:http://benfoster.io/blog/how-to-configure-kestrel-urls-in-aspnet-core-rc2 添加一個json文件,叫作hosting.json,意爲服務配置,固然起什麼名字不重要,裏面只須要添加一個節點便可,內容以下:github
{ "server.urls": "http://localhost:5001;http://localhost:5002" }
添加了一個server.urls節點,而後再修改Program.cs文件,web
運行後,顯示以下:json
5001和5002端口都開啓了監聽。app
這不由引發了個人興趣,便翻起了關於這一起的源碼。關於Hosting的源碼地址:https://github.com/aspnet/Hostingide
下面咱們層層深刻,究其緣由,查看IWebHost接口的Build方法:函數
/// <summary> /// Builds the required services and an <see cref="IWebHost"/> which hosts a web application. /// </summary> public IWebHost Build() { if (_webHostBuilt) { throw new InvalidOperationException(Resources.WebHostBuilder_SingleInstance); } _webHostBuilt = true; var hostingServices = BuildCommonServices(out var hostingStartupErrors); var applicationServices = hostingServices.Clone(); var hostingServiceProvider = GetProviderFromFactory(hostingServices); if (!_options.SuppressStatusMessages) { // Warn about deprecated environment variables if (Environment.GetEnvironmentVariable("Hosting:Environment") != null) { Console.WriteLine("The environment variable 'Hosting:Environment' is obsolete and has been replaced with 'ASPNETCORE_ENVIRONMENT'"); } if (Environment.GetEnvironmentVariable("ASPNET_ENV") != null) { Console.WriteLine("The environment variable 'ASPNET_ENV' is obsolete and has been replaced with 'ASPNETCORE_ENVIRONMENT'"); } if (Environment.GetEnvironmentVariable("ASPNETCORE_SERVER.URLS") != null) { Console.WriteLine("The environment variable 'ASPNETCORE_SERVER.URLS' is obsolete and has been replaced with 'ASPNETCORE_URLS'"); } } var logger = hostingServiceProvider.GetRequiredService<ILogger<WebHost>>(); // Warn about duplicate HostingStartupAssemblies foreach (var assemblyName in _options.GetFinalHostingStartupAssemblies().GroupBy(a => a, StringComparer.OrdinalIgnoreCase).Where(g => g.Count() > 1)) { logger.LogWarning($"The assembly {assemblyName} was specified multiple times. Hosting startup assemblies should only be specified once."); } AddApplicationServices(applicationServices, hostingServiceProvider); var host = new WebHost( applicationServices, hostingServiceProvider, _options, _config, hostingStartupErrors); try { host.Initialize(); return host; } catch { // Dispose the host if there's a failure to initialize, this should clean up // will dispose services that were constructed until the exception was thrown host.Dispose(); throw; }
在Build方法裏主要是初始化了一個WebHost對象,再進入WebHost的源代碼,學習
private void EnsureServer() { if (Server == null) { Server = _applicationServices.GetRequiredService<IServer>(); var serverAddressesFeature = Server.Features?.Get<IServerAddressesFeature>(); var addresses = serverAddressesFeature?.Addresses; if (addresses != null && !addresses.IsReadOnly && addresses.Count == 0) { var urls = _config[WebHostDefaults.ServerUrlsKey] ?? _config[DeprecatedServerUrlsKey]; if (!string.IsNullOrEmpty(urls)) { serverAddressesFeature.PreferHostingUrls = WebHostUtilities.ParseBool(_config, WebHostDefaults.PreferHostingUrlsKey); foreach (var value in urls.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { addresses.Add(value); } } } } }
不難找到是在上述方法裏面,添加的URL地址,在這行代碼中:網站
var urls = _config[WebHostDefaults.ServerUrlsKey] ?? _config[DeprecatedServerUrlsKey];
W這裏的URL判斷,若是當前默認的配置爲空則使用後面的配置,而DepreacatedServerUrlsKey在一開始就已經定義了,ui
private static readonly string DeprecatedServerUrlsKey = "server.urls";
該參數的默認值爲server.urls,因此咱們在hosting.json中直接配置該鍵值對,.net core啓動後會自動讀取配置文件,使用配置的端口。其餘相關配置,你們就自行搜索吧。
細心的小夥伴會發如今源代碼中,還有兩處是關於配置Url的,一處是在上面的Build方法中,有一處判斷:
if (Environment.GetEnvironmentVariable("ASPNETCORE_SERVER.URLS") != null)
{
Console.WriteLine("The environment variable 'ASPNETCORE_SERVER.URLS' is obsolete and has been replaced with 'ASPNETCORE_URLS'");
}
若是在環境變量中ASPNETCORE_SERVER.URLS不爲空的話,這個值就會替換ASPNETCORE_URLS的值,另外在WebHostBuilder的構造函數中,也有一段判斷代碼
if (string.IsNullOrEmpty(GetSetting(WebHostDefaults.ServerUrlsKey)))
{
// Try adding legacy url key, never remove this.
UseSetting(WebHostDefaults.ServerUrlsKey, Environment.GetEnvironmentVariable("ASPNETCORE_SERVER.URLS"));
}
若是獲取的默認的配置中urls的值爲空,那麼就啓用ASPNETCORE_SERVER.URLS環境變量中的配置,這也告訴咱們咱們還能夠把啓動的端口放到環境變量中,右鍵項目屬性,選擇調試,
添加環境變量ASPNETCORE_SERVER.URLS配置,以上就是我總結的修改默認啓動端口的全部方法了,若是還有其餘的方法,歡迎留言。
晚安。
掃描二維碼關注個人公衆號,共同窗習,共同進步!