背景

程序在发布部署时候,设置环境ASPNETCORE_URLS不生效,也没在代码里使用UseUrls("xxxx"),启动一直是http://localhost:5000.最后测试发现只有在appsettings.json中配置urls才生效,网上找了半天资料也没看到有什么问题。

最终翻看源代码,发现是在StartUp中的Configure替换了全局IConfiguration导致。

平时开发大体知道程序启动时候端口启用顺序是

UseUrls("xxx")> 环境变量 > 默认,具体是怎么确定使用哪个配置的,没找到资料,所有才有了本文。

启动地址配置的几种方式介绍
  1. 环境变量ASPNETCORE_URLS
#windows
set ASPNETCORE_URLS=http://localhost:6000
#linux
export ASPNETCORE_URLS=http://localhost:6000
  1. UseUrls("http://localhost:6000")
  2. appsettings.json新增urls或者server.urls配置
{
"urls":"http://localhost:6000;http://localhost:6001",
"server.urls":"http://localhost:6000;http://localhost:6001"
}
  1. 使用系统默认
说明

程序启动过程中,一个配置key会重复使用,先放这里

//WebHostDefaults.ServerUrlsKey如下
public static readonly string ServerUrlsKey = "urls";
Web项目启动地址配置说明

今天是介绍启动方式,所以web启动流程不是重点。直接进入正题。

Web启动最终是调用WebHost.StartAsync,源代码在这WebHost。其中有个方法EnsureServer来获取启动地址

private static readonly string DeprecatedServerUrlsKey = "server.urls";

//省略
var urls = _config[WebHostDefaults.ServerUrlsKey] ?? _config[DeprecatedServerUrlsKey];

是从全局IConfigration实例中获取启动地址。所以我的遇到问题这里就解决了。但环境变量UseUrls是如何解析并记载进来的呢?下面就开今天讲解。

环境变量配置详解

一般Web程序启动代码如下:

Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
}).Build().Run();

其中ConfigureWebHostDefaults的会用调用扩展方法ConfigureWebHost

public static IHostBuilder ConfigureWebHostDefaults(this IHostBuilder builder, Action<IWebHostBuilder> configure)
{
return builder.ConfigureWebHost(webHostBuilder =>
{
WebHost.ConfigureWebDefaults(webHostBuilder); configure(webHostBuilder);
});
}

以上代码都是定义在Microsoft.Extensions.Hosting中。

继续看ConfigureWebHost代码,这个方法就定义在Microsoft.AspNetCore.Hosting程序集中了。

public static IHostBuilder ConfigureWebHost(this IHostBuilder builder, Action<IWebHostBuilder> configure)
{
//这里会加载环境变量
var webhostBuilder = new GenericWebHostBuilder(builder);
//这里会调用UseUrls等扩展方法
configure(webhostBuilder);
builder.ConfigureServices((context, services) => services.AddHostedService<GenericWebHostService>());
return builder;
}

GenericWebHostBuilder 构造函数里有如下代码,用来初始化配置,最终添加到全局

IConfiguration实例中,也就是HostIConfiguration实例。

builder.ConfigureServices((context, services) => services.AddHostedService());这个是web启动重点,有兴趣的可以看下

//加入环境变量配置
_config = new ConfigurationBuilder()
.AddEnvironmentVariables(prefix: "ASPNETCORE_")
.Build();
//把配置加载到Host
_builder.ConfigureHostConfiguration(config =>
{
config.AddConfiguration(_config); // We do this super early but still late enough that we can process the configuration
// wired up by calls to UseSetting
ExecuteHostingStartups();
})

AddEnvironmentVariables环境变量解析最终会使用EnvironmentVariablesConfigurationProvider,有兴趣的可以看下AddEnvironmentVariables源代码EnvironmentVariablesConfigurationProvider解析环境的方法如下。

public override void Load()
{
Load(Environment.GetEnvironmentVariables());
} internal void Load(IDictionary envVariables)
{
var data = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
//这里是筛选ASPNETCORE_开头的环境变量
var filteredEnvVariables = envVariables
.Cast<DictionaryEntry>()
.SelectMany(AzureEnvToAppEnv)
.Where(entry => ((string)entry.Key).StartsWith(_prefix, StringComparison.OrdinalIgnoreCase)); foreach (var envVariable in filteredEnvVariables)
{
//这里会把前缀去掉加到配置里
var key = ((string)envVariable.Key).Substring(_prefix.Length);
data[key] = (string)envVariable.Value;
} Data = data;
}

IConfiguration中的key是不区分大小写的,所有最终的效是在全局IConfiguration中新增一条key为urls的记录。

而如果使用默认Host.CreateDefaultBuilder()appsettings.json中的配置会先加载。

如果在appsettings.json中配置urls的话,环境变量也定义了,就会被环境变量的覆盖掉。

UseUrls解析

UseUrls解析最终会调用GenericWebHostBuilder中的UseSetting

//UseUrls代码如下
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));
} //GenericWebHostBuilder中的UseSetting
public IWebHostBuilder UseSetting(string key, string value)
{
_config[key] = value;
return this;
}

由于这个方法是在 new GenericWebHostBuilder(builder);

之后调用,就是 configure(webhostBuilder);,上面代码也有说明。所以IConfigurationurls如果有值,又会被覆盖掉。所以优先级最高的是UseUrls()

默认地址

假如以上3种配置都没有,就是地址为空,会使用默认策略。这里是源代码,下面是默认策略使用的地址

 /// <summary>
/// The endpoint Kestrel will bind to if nothing else is specified.
/// </summary>
public static readonly string DefaultServerAddress = "http://localhost:5000"; /// <summary>
/// The endpoint Kestrel will bind to if nothing else is specified and a default certificate is available.
/// </summary>
public static readonly string DefaultServerHttpsAddress = "https://localhost:5001";
结论
  1. 启动端口设置优先级如下:

    UseUrls("xxxx") > 环境变量 > appsetting.json配置urls>默认地址
  2. 不要随意替换全局的IConfiguration,如果不手动加入环境变量解析的话,会丢失一部分配置数据。
  3. 将自己的配置注入的全局,可以使用以下方式,这样就会把配置追加到全局的IConfiguration
 Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(builder =>
{
builder.UseStartup<Startup>();
}).ConfigureAppConfiguration(config =>
{
config.AddJsonFile("config.json", true, true);
}).Build().Run();

作者:cgyqu

出处:https://www.cnblogs.com/cgyqu/p/12169014.html

本站使用「署名 4.0 国际」创作共享协议,转载请在文章明显位置注明作者及出处。

NetCore 启动地址配置详解的更多相关文章

  1. Java从入门到精通——数据库篇Mongo DB 安装启动及配置详解

    一.概述     Mongo DB 下载下来以后我们应该如何去安装启动和配置才能使用Mongo DB,本篇博客就给大家讲述一下Mongo DB的安装启动及配置详解. 二.安装 1.下载Mongo DB ...

  2. GRUB2配置详解:默认启动项,超时时间,隐藏引导菜单,配置文件详解,图形化配置

    配置文件详解: /etc/default/grub # 设定默认启动项,推荐使用数字 GRUB_DEFAULT=0 # 注释掉下面这行将会显示引导菜单 #GRUB_HIDDEN_TIMEOUT=0 # ...

  3. Spring Boot 启动(二) 配置详解

    Spring Boot 启动(二) 配置详解 Spring 系列目录(https://www.cnblogs.com/binarylei/p/10198698.html) Spring Boot 配置 ...

  4. apache 虚拟主机详细配置:http.conf配置详解

    apache 虚拟主机详细配置:http.conf配置详解 Apache的配置文件http.conf参数含义详解 Apache的配置由httpd.conf文件配置,因此下面的配置指令都是在httpd. ...

  5. tomcat的配置详解:[1]tomcat绑定域名

    转自:http://jingyan.baidu.com/article/7e440953dc096e2fc0e2ef1a.html tomcat的配置详解:[1]tomcat绑定域名分步阅读 在jav ...

  6. WebsitePanel(wsp)配置详解(安装指南)

    WebsitePanel(wsp)配置详解(安装指南) 铁卫士原创 估计很多同学都还不知道WebsitePanel是什么东东吧,WebsitePanel简称wsp是微软旗下,开源免费的虚拟主机系统,我 ...

  7. maven常用插件配置详解

    常用插件配置详解Java代码    <!-- 全局属性配置 --> <properties> <project.build.name>tools</proje ...

  8. Apache2.2+Tomcat7.0整合配置详解

    一.简单介绍 Apache.Tomcat Apache HTTP Server(简称 Apache),是 Apache 软件基金协会的一个开放源码的网页服务器,可以在 Windows.Unix.Lin ...

  9. Nginx+Tomcat的服务器端环境配置详解

    这篇文章主要介绍了Nginx+Tomcat的服务器端环境配置详解,包括Nginx与Tomcat的监控开启方法,需要的朋友可以参考下 Nginx+tomcat是目前主流的Javaweb架构,如何让ngi ...

随机推荐

  1. js面向对象(对象/类/工厂模式/构造函数/公有和原型)

    https://www.cnblogs.com/sandraryan/ 什么是对象 js中一切都是对象(有行为和特征).js允许自定义对象,也提供了内建对象(string date math等) 对象 ...

  2. HDU 1026 BSF+优先队列+记录路径、

    #include<iostream> #include<cmath> #include<cstring> #include<cstdio> #inclu ...

  3. Array.from()类数组转化为数组的用法

    类数组对象转化为数组 let arrayLike = { '0': 'a', '1': 'b', '2': 'c', length: 3 }; let arr = Array.from(arrayLi ...

  4. git clone出现Permission denied (publickey)解决办法

    一.错误 git clone git@gitee.com:wangzaiplus/xxx.git, 出现Permission denied (publickey) 二.原因 无权限, 未将公钥添加至G ...

  5. svn 删除、移动和改名

    删除.移动和改名 Subversion allows renaming and moving of files and folders. So there are menu entries for d ...

  6. P1099 双连击

    题目描述 我们假设一个二位整数 \(N(10 \le N \le 99)\) ,它的十位上的数字是 \(A\) ,个位上的数字是 \(B\) ,如果 \(A\) 和 \(B\) 的比例关系满足 \(A ...

  7. linux 字符设备注册

    如我们提过的, 内核在内部使用类型 struct cdev 的结构来代表字符设备. 在内核调用你 的设备操作前, 你编写分配并注册一个或几个这些结构. [11] 11为此, 你的代码应当包含 < ...

  8. P1001 A+B+C Problem

    题目描述 输入三个整数 \(a,b,c\) ,计算它们的和并将结果输出. 输入格式 输入一行,三个整数 \(a,b,c\) ,每个整数之间以一个空格隔开 \((0 \le a,b,c \le 1000 ...

  9. substring和substr的区别和使用

    第一反应是都是截取字符串的方法,好像平常使用的时候也没太注意区分这俩,今天看到正好来区分一下 substring(start,[end]) 如果省略end,那么截取的是从指定位置到末尾 var str ...

  10. 【37.48%】【hdu 2587】How far away ?(3篇文章,3种做法,LCA之树上倍增)

    Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submission(s) ...