NetCore 启动地址配置详解
背景
程序在发布部署时候,设置环境ASPNETCORE_URLS
不生效,也没在代码里使用UseUrls("xxxx")
,启动一直是http://localhost:5000
.最后测试发现只有在appsettings.json
中配置urls
才生效,网上找了半天资料也没看到有什么问题。
最终翻看源代码,发现是在StartUp
中的Configure
替换了全局IConfiguration
导致。
平时开发大体知道程序启动时候端口启用顺序是
UseUrls("xxx")
> 环境变量 > 默认,具体是怎么确定使用哪个配置的,没找到资料,所有才有了本文。
启动地址配置的几种方式介绍
- 环境变量
ASPNETCORE_URLS
#windows
set ASPNETCORE_URLS=http://localhost:6000
#linux
export ASPNETCORE_URLS=http://localhost:6000
UseUrls("http://localhost:6000")
appsettings.json
新增urls
或者server.urls
配置
{
"urls":"http://localhost:6000;http://localhost:6001",
"server.urls":"http://localhost:6000;http://localhost:6001"
}
- 使用系统默认
说明
程序启动过程中,一个配置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
实例中,也就是Host
中IConfiguration
实例。
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);
,上面代码也有说明。所以IConfiguration
中urls如果有值,又会被覆盖掉。所以优先级最高的是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";
结论
- 启动端口设置优先级如下:
UseUrls("xxxx")
> 环境变量 >appsetting.json
配置urls
>默认地址 - 不要随意替换全局的
IConfiguration
,如果不手动加入环境变量解析的话,会丢失一部分配置数据。 - 将自己的配置注入的全局,可以使用以下方式,这样就会把配置追加到全局的
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 启动地址配置详解的更多相关文章
- Java从入门到精通——数据库篇Mongo DB 安装启动及配置详解
一.概述 Mongo DB 下载下来以后我们应该如何去安装启动和配置才能使用Mongo DB,本篇博客就给大家讲述一下Mongo DB的安装启动及配置详解. 二.安装 1.下载Mongo DB ...
- GRUB2配置详解:默认启动项,超时时间,隐藏引导菜单,配置文件详解,图形化配置
配置文件详解: /etc/default/grub # 设定默认启动项,推荐使用数字 GRUB_DEFAULT=0 # 注释掉下面这行将会显示引导菜单 #GRUB_HIDDEN_TIMEOUT=0 # ...
- Spring Boot 启动(二) 配置详解
Spring Boot 启动(二) 配置详解 Spring 系列目录(https://www.cnblogs.com/binarylei/p/10198698.html) Spring Boot 配置 ...
- apache 虚拟主机详细配置:http.conf配置详解
apache 虚拟主机详细配置:http.conf配置详解 Apache的配置文件http.conf参数含义详解 Apache的配置由httpd.conf文件配置,因此下面的配置指令都是在httpd. ...
- tomcat的配置详解:[1]tomcat绑定域名
转自:http://jingyan.baidu.com/article/7e440953dc096e2fc0e2ef1a.html tomcat的配置详解:[1]tomcat绑定域名分步阅读 在jav ...
- WebsitePanel(wsp)配置详解(安装指南)
WebsitePanel(wsp)配置详解(安装指南) 铁卫士原创 估计很多同学都还不知道WebsitePanel是什么东东吧,WebsitePanel简称wsp是微软旗下,开源免费的虚拟主机系统,我 ...
- maven常用插件配置详解
常用插件配置详解Java代码 <!-- 全局属性配置 --> <properties> <project.build.name>tools</proje ...
- Apache2.2+Tomcat7.0整合配置详解
一.简单介绍 Apache.Tomcat Apache HTTP Server(简称 Apache),是 Apache 软件基金协会的一个开放源码的网页服务器,可以在 Windows.Unix.Lin ...
- Nginx+Tomcat的服务器端环境配置详解
这篇文章主要介绍了Nginx+Tomcat的服务器端环境配置详解,包括Nginx与Tomcat的监控开启方法,需要的朋友可以参考下 Nginx+tomcat是目前主流的Javaweb架构,如何让ngi ...
随机推荐
- js面向对象(对象/类/工厂模式/构造函数/公有和原型)
https://www.cnblogs.com/sandraryan/ 什么是对象 js中一切都是对象(有行为和特征).js允许自定义对象,也提供了内建对象(string date math等) 对象 ...
- HDU 1026 BSF+优先队列+记录路径、
#include<iostream> #include<cmath> #include<cstring> #include<cstdio> #inclu ...
- Array.from()类数组转化为数组的用法
类数组对象转化为数组 let arrayLike = { '0': 'a', '1': 'b', '2': 'c', length: 3 }; let arr = Array.from(arrayLi ...
- git clone出现Permission denied (publickey)解决办法
一.错误 git clone git@gitee.com:wangzaiplus/xxx.git, 出现Permission denied (publickey) 二.原因 无权限, 未将公钥添加至G ...
- svn 删除、移动和改名
删除.移动和改名 Subversion allows renaming and moving of files and folders. So there are menu entries for d ...
- P1099 双连击
题目描述 我们假设一个二位整数 \(N(10 \le N \le 99)\) ,它的十位上的数字是 \(A\) ,个位上的数字是 \(B\) ,如果 \(A\) 和 \(B\) 的比例关系满足 \(A ...
- linux 字符设备注册
如我们提过的, 内核在内部使用类型 struct cdev 的结构来代表字符设备. 在内核调用你 的设备操作前, 你编写分配并注册一个或几个这些结构. [11] 11为此, 你的代码应当包含 < ...
- P1001 A+B+C Problem
题目描述 输入三个整数 \(a,b,c\) ,计算它们的和并将结果输出. 输入格式 输入一行,三个整数 \(a,b,c\) ,每个整数之间以一个空格隔开 \((0 \le a,b,c \le 1000 ...
- substring和substr的区别和使用
第一反应是都是截取字符串的方法,好像平常使用的时候也没太注意区分这俩,今天看到正好来区分一下 substring(start,[end]) 如果省略end,那么截取的是从指定位置到末尾 var str ...
- 【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) ...