.Net Core 修改預設的啟動埠

AllenChoi0912發表於2018-03-12

    今天無意中發現一個變化,因為很久沒看.net core的專案了,發現專案啟動的預設埠已經不是5000了,記得很清楚,最早那還是.net core 1.x版本的時候,每次啟動都會預設是5000埠號,而現在不是了。藉此機會在來說一下,關於.net core專案修改預設埠號的解決方案,我們最熟知的是一種解決方案就是直接在Program.cs中建立WebHost物件的時候,使用UseUrls()方法,配置要使用的埠,如下所示:

這是我們再熟悉不過的修改方法了,啟動以後,5001和5002埠都會開啟監聽,所以我們通過這兩個地址都會訪問到我們的網站。但是這種方式的缺點就是我們要修改程式碼,重新編譯執行,這並不是我們想要的最好的解決方案,如果可以直接在配置檔案中配置就完美了,便在一個個人部落格裡看到了一個方法,地址:http://benfoster.io/blog/how-to-configure-kestrel-urls-in-aspnet-core-rc2 新增一個json檔案,叫做hosting.json,意為服務配置,當然起什麼名字不重要,裡面只需要新增一個節點即可,內容如下:

{
  "server.urls": "http://localhost:5001;http://localhost:5002"
}

新增了一個server.urls節點,然後再修改Program.cs檔案,

執行後,顯示如下:

5001和5002埠都開啟了監聽。

這不禁引起了我的興趣,便翻起了關於這一塊兒的原始碼。關於Hosting的原始碼地址:https://github.com/aspnet/Hosting

下面我們層層深入,究其原因,檢視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在一開始就已經定義了,

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配置,以上就是我總結的修改預設啟動埠的所有方法了,如果還有其他的方法,歡迎留言。

晚安。


掃描二維碼關注我的公眾號,共同學習,共同進步!

相關文章