ASP.NET Core中的配置
配置
配置来源
- 命令行参数
- 自定义提供程序
- 目录文件
- 环境变量
- 内存中的.NET 对象
- 文件
默认配置
- CreateDefaultBuilder方法提供有默认配置,在这个方法中会接收前缀为ASPNETCORE_的变量和命令行参数以及appsettings.json和appsettings.{Environment}.json等,可以通过下面的源码看到,注意配置文件的顺序
- 一般顺序为
- 文件
- Azure
- 用户机密(生产中没有)
- 环境变量
- 命令行参数
命令行参数可以更新替换相关的程序设置,与前面提到的顺序有关,详细见下面的约定
public static IWebHostBuilder CreateDefaultBuilder(string[] args)
{
var builder = new WebHostBuilder();
if (string.IsNullOrEmpty(builder.GetSetting(WebHostDefaults.ContentRootKey)))
{
builder.UseContentRoot(Directory.GetCurrentDirectory());
}
if (args != null)
{
builder.UseConfiguration(new ConfigurationBuilder().AddCommandLine(args).Build());
}
builder.UseKestrel((builderContext, options) =>
{
options.Configure(builderContext.Configuration.GetSection("Kestrel"));
})
.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
if (env.IsDevelopment())
{
var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
if (appAssembly != null)
{
config.AddUserSecrets(appAssembly, optional: true);
}
}
config.AddEnvironmentVariables();
if (args != null)
{
config.AddCommandLine(args);
}
})
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
logging.AddEventSourceLogger();
})
.ConfigureServices((hostingContext, services) =>
{
// Fallback
services.PostConfigure<HostFilteringOptions>(options =>
{
if (options.AllowedHosts == null || options.AllowedHosts.Count == 0)
{
// "AllowedHosts": "localhost;127.0.0.1;[::1]"
var hosts = hostingContext.Configuration["AllowedHosts"]?.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
// Fall back to "*" to disable.
options.AllowedHosts = (hosts?.Length > 0 ? hosts : new[] { "*" });
}
});
// Change notification
services.AddSingleton<IOptionsChangeTokenSource<HostFilteringOptions>>(
new ConfigurationChangeTokenSource<HostFilteringOptions>(hostingContext.Configuration));
services.AddTransient<IStartupFilter, HostFilteringStartupFilter>();
})
.UseIIS()
.UseIISIntegration()
.UseDefaultServiceProvider((context, options) =>
{
options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
});
return builder;
}
相关约定
- 键不区分大小写,但是linux好像区分,所以最好还是有区分的好
- 同键值会被覆盖,以最后的为准
- 环境变量中,冒号分隔不适应用所有的平台,但是双下划线支持所有的平台
- Azure中用两个破折号,国内有阿里的比较多
- ConfigurationBinder支持配置到对象的转换,有Bind和Get<>的两种方式,注意区分,建议用Get
- 值是字符串且NULL不能出现在配置文件中也不能绑定到相应的对象中去
参数提供程序
主机通过ConfigureAppConfiguration指定应用配置程序
命令行参数提供程序
配置
- 其实CreateDefaultBuider已经支持了,但是如果需要应用程序配置并能实现覆盖的功能就需要在CnfigureAppConfiguration中添加并且在最后添加AddCommandLine如下:
//一种写法
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
// Call other providers here and call AddCommandLine last.
config.AddCommandLine(args);
})
.UseStartup<Startup>();
//另一种写法
var config = new ConfigurationBuilder()
// Call additional providers here as needed.
// Call AddCommandLine last to allow arguments to override other configuration.
.AddCommandLine(args)
.Build();
var host = new WebHostBuilder()
.UseConfiguration(config)
.UseKestrel()
.UseStartup<Startup>();
使用
- 命令行后有两种赋值方式,等号和空格(键前必顺有--或/),不要混合使用(知道的多不是让你乱用的,你的明白)
- 等号赋值 值可以为null
dotnet run CommandLineKey1=value1 --CommandLineKey2=value2 /CommandLineKey3=value3
dotnet run --CommandLineKey1 value1 /CommandLineKey2 value2
dotnet run CommandLineKey1= CommandLineKey2=value2
- 交换映射
就是给命令行的键值改名,以-开头的必顺要交换,再加上默认提供程序没有注入的地方,如果硬传将造成格式异常,所以可以通过AddCommandLine在ConfigureAppConfiguration中进行传递
public static readonly Dictionary<string, string> _switchMappings =
new Dictionary<string, string>
{
{ "-CLKey1", "CommandLineKey1" },
{ "-CLKey2", "CommandLineKey2" }
};
WebHost.CreateDefaultBuilder()
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddCommandLine(args, _switchMappings);
})
.UseStartup<Startup>();
环境变量提供程序
注意:分隔无法适应所有的平台,__可以,由加载顺序可以知道环境变量是可以替换appsettings文件中的配置,注意默认的环境变量前缀是ASPNETCORE_所以为了区分自己添加的不要用这个前缀了,前缀尽量见名知义,一个结果 就是能自解
配置
与命令行一样在ConfigureAppConfiguration中添加并声明前缀,如下:
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
// Call additional providers here as needed.
// Call AddEnvironmentVariables last if you need to allow environment
// variables to override values from other providers.
config.AddEnvironmentVariables(prefix: "PREFIX_");
})
.UseStartup<Startup>();
//二种写法
var config = new ConfigurationBuilder()
.AddEnvironmentVariables()
.Build();
var host = new WebHostBuilder()
.UseConfiguration(config)
.UseKestrel()
.UseStartup<Startup>();
使用
就是配置系统级的环境变量,不同的系统不太一样,windows可以在属性->环境变境中找到,linux可以命令行配置也可以直接改文件
文件配置提供程序(重点,重点,使用比较多)
首先明白不论何种文件,一定要能根据路径找到,所以我们一定要通过SetBasePath设置基路径,然后再是不同的文件
INI文件
配置
与前面的一样也是在ConfigureAppConfiguration中添加
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(Directory.GetCurrentDirectory());
config.AddIniFile("config.ini", optional: true, reloadOnChange: true);
})
.UseStartup<Startup>();
//二种
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddIniFile("config.ini", optional: true, reloadOnChange: true)
.Build();
var host = new WebHostBuilder()
.UseConfiguration(config)
.UseKestrel()
.UseStartup<Startup>();
JSON文件
配置
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(Directory.GetCurrentDirectory());
config.AddJsonFile("config.json", optional: true, reloadOnChange: true);
})
.UseStartup<Startup>();
//二种
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("config.json", optional: true, reloadOnChange: true)
.Build();
var host = new WebHostBuilder()
.UseConfiguration(config)
.UseKestrel()
.UseStartup<Startup>();
XML文件
配置
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(Directory.GetCurrentDirectory());
config.AddXmlFile("config.xml", optional: true, reloadOnChange: true);
})
.UseStartup<Startup>();
//另一种写法(二种)
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddXmlFile("config.xml", optional: true, reloadOnChange: true)
.Build();
var host = new WebHostBuilder()
.UseConfiguration(config)
.UseKestrel()
.UseStartup<Startup>();
Key-pre-file配置提供程序
使用目录的文件作为配置,键是文件名,值是包含在文件的内容。路径必顺是绝对路径。双下划线字符 (__) 用作文件名中的配置键分隔符。 例如,文件名 Logging__LogLevel__System 生成配置键 Logging:LogLevel:System
配置
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(Directory.GetCurrentDirectory());
var path = Path.Combine(Directory.GetCurrentDirectory(), "path/to/files");
config.AddKeyPerFile(directoryPath: path, optional: true);
})
.UseStartup<Startup>();
//二种
var path = Path.Combine(Directory.GetCurrentDirectory(), "path/to/files");
var config = new ConfigurationBuilder()
.AddKeyPerFile(directoryPath: path, optional: true)
.Build();
var host = new WebHostBuilder()
.UseConfiguration(config)
.UseKestrel()
.UseStartup<Startup>();
内存配置提供程序
就是内存中的对象(字典对象之流)结构为IEnumerable<KeyValuePair<String,String>>
配置
public static readonly Dictionary<string, string> _dict =
new Dictionary<string, string>
{
{"MemoryCollectionKey1", "value1"},
{"MemoryCollectionKey2", "value2"}
};
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddInMemoryCollection(_dict);
})
.UseStartup<Startup>();
//二种
var dict = new Dictionary<string, string>
{
{"MemoryCollectionKey1", "value1"},
{"MemoryCollectionKey2", "value2"}
};
var config = new ConfigurationBuilder()
.AddInMemoryCollection(dict)
.Build();
var host = new WebHostBuilder()
.UseConfiguration(config)
.UseKestrel()
.UseStartup<Startup>();
获取配置内容
- GetSection 获取指定子节键提取值
- GetChildren 获取节点的值
- Bind 把字符串构造为POCO对象
- Get 绑定并返回指定类型 Get 比使用 Bind 更方便
绑定是按约定提供的。 不需要自定义配置提供程序实现数组绑定。
可以在代码中读到相应的值
var configEntryFilter = new string[] { "ASPNETCORE_", "urls", "Logging", "ENVIRONMENT", "contentRoot", "AllowedHosts", "applicationName", "CommandLine" };
var config = cfg.AsEnumerable();
FilteredConfiguration = config.Where(
kvp => config.Any(
i => configEntryFilter.Any(prefix => kvp.Key.StartsWith(prefix))));
var starship = new Starship();
cfg.GetSection("starship").Bind(starship);
Starship = starship;
TvShow = cfg.GetSection("tvshow").Get<TvShow>();
ArrayExample = cfg.GetSection("array").Get<ArrayExample>();
JsonArrayExample = cfg.GetSection("json_array").Get<JsonArrayExample>();
Customer customer = cfg.GetSection("customer").Get<Customer>();
var value1 = cfg.GetValue<object>("name", "read error");
自定义配置提供程序
该示例应用演示了如何使用实体框架 (EF) 创建从数据库读取配置键值对的基本配置提供程序。
倒着分析(正分析看官文)
- 我们要添加一个配置到ConfigurationBuilder中(可以用扩展 AddEFConfiguration)
- 要扩展我们要有配置内容类来作为载体EFConfigurationContext
- 我们要用对应的内容解析类来提供解析 EFConfigurationProvider
- 最后我们要有解析出来对应的对象来进行绑定 EFConfigurationValue
-最后我们要注入到ConfigureServices和Configure中这样就可以在指定的作用域内使用了
详见我抄官网上的git源码点击跳转,同样官网上的源码也是可以运行的。
ASP.NET Core中的配置的更多相关文章
- (11)ASP.NET Core 中的配置一(Configuration)
1.前言 ASP.NET Core在应用程序上引入Microsoft.Extensions.Configuration配置,可以支持多种方式配置,包括命令行配置.环境变量配置.文件配置.内存配置,自定 ...
- (12)ASP.NET Core 中的配置二(Configuration)
1.内存配置 MemoryConfigurationProvider使用内存中集合作为配置键值对.若要激活内存中集合配置,请在ConfigurationBuilder的实例上调用AddInMemory ...
- 聊聊ASP.NET Core中的配置
作为软件开发人员,我们当然喜欢一些可配置选项,尤其是当它允许我们改变应用程序的行为而无需修改或编译我们的应用程序时.无论你是使用新的还是旧的.NET时,可能希望利用json文件的配置.在这篇文章中, ...
- 3、带你一步一步学习ASP.NET Core中的配置之Configuration
如果你是刚接触ASP.NET Core的学习的话,你会注意到:在ASP.NET Core项目中,看不到.NET Fraemwork时代中的web.config文件和app.config文件了.那么你肯 ...
- ASP.NET Core 中的配置
目录 以键-值对的形式读取配置 多环境配置 读取结构化的配置数据 参考 .NET Core 定义配置的方式不同于之前 NET 版本,之前是依赖于 System.Configuration 的 app. ...
- ASP.NET Core 学习笔记 第四篇 ASP.NET Core 中的配置
前言 说道配置文件,基本大多数软件为了扩展性.灵活性都会涉及到配置文件,比如之前常见的app.config和web.config.然后再说.NET Core,很多都发生了变化.总体的来说技术在进步,新 ...
- ASP.NET Core开发-如何配置Kestrel 网址Urls
ASP.NET Core中如何配置Kestrel Urls呢,大家可能都知道使用UseUrls() 方法来配置. 今天给介绍全面的ASP.NET Core 配置 Urls,使用多种方式配置Urls. ...
- ASP.NET Core中如何调整HTTP请求大小的几种方式
一.前言 一般的情况下,我们都无需调用HTTP请求的大小,只有在上传一些大文件,或者使用HTTP协议写入较大的值时(如调用WebService)才可能会调用HTTP最大请求值. 在ASP.NET Co ...
- asp.net core 系列 10 配置configuration (上)
一. ASP.NET Core 中的配置概述 ASP.NET Core 中的应用配置是基于键值对,由configuration 程序提供. configuration 将从各种配置源提供程序操作键 ...
随机推荐
- [STL] Implement "vector", ”deque“ and "list"
vector “可增的”数组 vector是一块连续分配的内存,从数据安排的角度来讲,和数组极其相似. 不同的地方就是: (1) 数组是静态分配空间,一旦分配了空间的大小,就不可再改变了: (2) v ...
- 用git提交新项目到github
1.(先进入项目文件夹)通过命令 git init 把这个目录变成git可以管理的仓库 git init 2.把文件添加到版本库中,使用命令 git add .添加到暂存区里面去,不要忘记后面的小数点 ...
- pycharm使用sublime/boxy配色方案
# 展示效果图 1. github官网连接:https://github.com/simoncos/pycharm-monokai 2.克隆代码并解压文件 3.PyCharm -> File - ...
- 阿里云服务器ecs配置之安装jdk
一.安装环境 操作系统:Centos 7.4 JDK版本:1.8 工具:Xshell5.Xftp5 二.安装步骤 第一步:下载安装包 (官网)链接: 下载适合自己系统的jdk版本,如图:我下载的是64 ...
- SpringBootSecurity学习(15)前后端分离版之 OAuth2.0简单示例
OAuth2.0 OAuth 引入了一个授权层,用来分离两种不同的角色:客户端和资源所有者.客户端来申请资源,资源所有者同意以后,资源服务器可以向客户端颁发令牌.客户端通过令牌,去请求数据.也就是说, ...
- Windows Error的错误代码
时不时会用到,记录下 0操作成功完成. 1功能错误. 2系统找不到指定的文件. 3系统找不到指定的路径. 4系统无法打开文件. 5拒绝访问. 6句柄无效. 7存储控制块被损坏. 8存储空间不足,无法处 ...
- 主动降噪技术(ANC)的前生今世–行业分析
一 原始玩家 1978年,创始人Amar G. Bose博士在从欧洲飞往波士顿的飞机上,发现飞机引擎的噪音扫净了他戴耳机欣赏音乐的兴致.这激发了他在BOSE公司进行一项消噪科技的研究.弹指之间,十年过 ...
- Vue/React圆环进度条
数据展示,一直是各行各业乐此不疲的需求,具体到前端开发行业,则是各种各种图表数据展示,各种表格数据展示,烦不胜烦(繁不胜繁)! 前几天刚做了折线图.柱状图.饼状图之类的图表数据展示效果,今天又碰到了类 ...
- 利用C++实现模块隐藏(R3层断链)
一.模块隐藏的实现原理 普通API查找模块实现思路:其通过查询在R3中的PEB(Process Environment Block 进程环境块)与TEB(Thread Environment Bloc ...
- 原生js动态创建文本内容的几种方式
1.通过CreateTextNode文本节点 首先创建该元素(元素节点),然后向一个已存在的元素追加该文本节点 <!DOCTYPE html> <html> <body& ...