.net Core 启动域名及端口配置

原文链接:http://www.cnblogs.com/Hai--D/p/5842842.html (写的非常好,推荐!)


1.IIS集成

如果通过IIS当宿主的话,那这些都不是事情,强大的IIS可以帮助我们对站点的域名、端口等等等等的配置。至于如何在IIS上部署asp.net core的web应用,就不是这里的重点。大致简单的描述一下:

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

.net Core 启动域名及端口配置

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

               server host 是否安装成功iis模块与处理程序映射中查看如下

.net Core 启动域名及端口配置

然后建立站点,指定到发布站点的文件

最后就是应该程序池配置,选择无托管,这样有server host转发请求。

.net Core 启动域名及端口配置

 

2.Linux环境

具体安装就不说了,也是一大堆。根据官网指示,也就是安装.net core运行环境就可以运行了。

这里推荐一篇博文,大家自行参考 将ASP.NET Core应用程序部署至生产环境中(CentOS7)

 

回到重点,如何配置url及端口参数

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

.net Core 启动域名及端口配置
public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseUrls("http://localhost:5001")
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }
.net Core 启动域名及端口配置

这种方法不灵活,即使通过增加配置文件去读,也不是那么优雅。这个时候,本人就觉得微软肯定不会推荐这么用的,于是继续找。

2.通过环境变量

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

虽然还是通过配置文件配置,但是它不向其他文章,不需要读出配置信息,直接绑定就能用,还是贴代码看:

hosting.json

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

Program.cs

.net Core 启动域名及端口配置
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();
}
.net Core 启动域名及端口配置

这样它也能监听

Now listening on: http://localhost:60000

Now listening on: http://localhost:60001

是不是很神奇!实战受不了了,扣源码!目前为止.net core最好的地方就是有源码!

通过溯源,我们可以知道主要是 WebHostBuilder 这个类,在Microsoft.AspNetCore.Hosting命名空间下。

主要的方法还是Build

.net Core 启动域名及端口配置
        /// <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;
        }
.net Core 启动域名及端口配置

这边主要是构建一个WebHost对象,然后更进去看

通过Initialize方法查看源代码,我们可以知道是EnsureServer这个方法创建的url地址

.net Core 启动域名及端口配置
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");
            }
        }
    }
}
.net Core 启动域名及端口配置

这里我们可以知道,原来它自己会从配置里面去读 _config[WebHostDefaults.ServerUrlsKey] 和 _config[DeprecatedServerUrlsKey]

WebHostDefaults.ServerUrlsKey的值是固定值

.net Core 启动域名及端口配置

DeprecatedServerUrlsKey的值在WebHost这个对象一开始就定义了

.net Core 启动域名及端口配置

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

 

总结:

综上所述,asp.net core启动的时候会自行读取环境变量里面的配置,实际点就是在项目属性里面增加如下配置:

.net Core 启动域名及端口配置

已控制台方式启动,发现已经切换了端口。

那么这个是在开发环境,如何在产线部署呢。这个也很简单,以linux上部署为例,以守护进程supervisor启动程序,在supervisor的启动配置里面增加环境变量:

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

大功告成!一行代码都不需要改,哈哈~