.net core 啟動域名及端口配置


前兩天轉載一篇.net core 啟動分析,由於發布時候一直糾結在默認5000端口上,所以好好研究了一下。

1.IIS集成

如果通過IIS當宿主的話,那這些都不是事情,強大的IIS可以幫助我們對站點的域名、端口等等等等的配置。至於如何在IIS上部署asp.net core的web應用,就不是這里的重點。大致簡單的描述一下:

需要下載Net Core SDK 與 Server Hosting,下載地址https://www.microsoft.com/net/download

 安裝完查看.net core sdk是否安裝成功命令行dotnet info 

               server host 是否安裝成功iis模塊與處理程序映射中查看如下

然后建立站點,指定到發布站點的文件

最后就是應該程序池配置,選擇無托管,這樣有server host轉發請求。

 

2.Linux環境

具體安裝就不說了,也是一大堆。根據官網指示,也就是安裝.net core運行環境就可以運行了。

這里推薦一篇博文,大家自行參考 將ASP.NET Core應用程序部署至生產環境中(CentOS7)

 

回到重點,如何配置url及端口參數

1.在Program的Main方法里面指定

復制代碼
public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseUrls("http://localhost:5001")
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }
復制代碼

這種方法不靈活,即使通過增加配置文件去讀,也不是那么優雅。這個時候,本人就覺得微軟肯定不會推薦這么用的,於是繼續找。

2.通過環境變量

網上看到有一篇How to configure Kestrel URLs in ASP.NET Core RC2

雖然還是通過配置文件配置,但是它不向其他文章,不需要讀出配置信息,直接綁定就能用,還是貼代碼看:

hosting.json

{
  "server.urls": "http://localhost:60000;http://localhost:60001"
}

Program.cs

復制代碼
public static void Main(string[] args)
{
    var config = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("hosting.json", optional: true)
        .Build();

    var host = new WebHostBuilder()
        .UseKestrel()
        .UseConfiguration(config)
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .Build();

    host.Run();
}
復制代碼

這樣它也能監聽

Now listening on: http://localhost:60000

Now listening on: http://localhost:60001

是不是很神奇!實戰受不了了,扣源碼!目前為止.net core最好的地方就是有源碼!

通過溯源,我們可以知道主要是 WebHostBuilder 這個類,在Microsoft.AspNetCore.Hosting命名空間下。

主要的方法還是Build

復制代碼
        /// <summary>
        /// Builds the required services and an <see cref="IWebHost"/> which hosts a web application.
        /// </summary>
        public IWebHost Build()
        {
            // 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 hostingServices = BuildHostingServices();
            var hostingContainer = hostingServices.BuildServiceProvider();

            var host = new WebHost(hostingServices, hostingContainer, _options, _config);

            host.Initialize();

            return host;
        }
復制代碼

這邊主要是構建一個WebHost對象,然后更進去看

通過Initialize方法查看源代碼,我們可以知道是EnsureServer這個方法創建的url地址

復制代碼
private void EnsureServer()
{
    if (Server == null)
    {
        Server = _applicationServices.GetRequiredService<IServer>();

        var addresses = Server.Features?.Get<IServerAddressesFeature>()?.Addresses;
        if (addresses != null && !addresses.IsReadOnly && addresses.Count == 0)
        {
            var urls = _config[WebHostDefaults.ServerUrlsKey] ?? _config[DeprecatedServerUrlsKey];
            if (!string.IsNullOrEmpty(urls))
            {
                foreach (var value in urls.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    addresses.Add(value);
                }
            }

            if (addresses.Count == 0)
            {
                // Provide a default address if there aren't any configured.
                addresses.Add("http://localhost:5000");
            }
        }
    }
}
復制代碼

這里我們可以知道,原來它自己會從配置里面去讀 _config[WebHostDefaults.ServerUrlsKey] 和 _config[DeprecatedServerUrlsKey]

WebHostDefaults.ServerUrlsKey的值是固定值

DeprecatedServerUrlsKey的值在WebHost這個對象一開始就定義了

哦!真相大白了。所以我們在配置文件里面設置“server.urls”就可以了。

 

總結:

綜上所述,asp.net core啟動的時候會自行讀取環境變量里面的配置,實際點就是在項目屬性里面增加如下配置:

已控制台方式啟動,發現已經切換了端口。

那么這個是在開發環境,如何在產線部署呢。這個也很簡單,以linux上部署為例,以守護進程supervisor啟動程序,在supervisor的啟動配置里面增加環境變量:

environment=ASPNETCORE_URLS='http://*:5001'

原文鏈接:https://www.cnblogs.com/Hai--D/p/5842842.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM