Net core学习系列(九)——Net Core配置
一、简介
NET Core为我们提供了一套用于配置的API,它为程序提供了运行时从文件、命令行参数、环境变量等读取配置的方法。配置都是键值对的形式,并且支持嵌套,.NET Core还内建了从配置反序列化为POCO对象的支持。
目前支持以下配置Provider:
- 文件(INI,JSON,XML)
- 命令行参数
- 环境变量
- 内存中的.NET对象
- User Secrets
- Azure Key Vault
如果现有Provider不能满足你的使用场景,还允许自定义Provider,比如从数据库中读取。
二、配置相关的包
包管理器中搜索“Microsoft.Extensions.Configuration",所有与配置相关的包都会列举出来

从包的名称基本就可以看出它的用途,比如Microsoft.Extensions.Configuration.Json是Json配置的Provider,Microsoft.Extensions.Configuration.CommandLine是命令行参数配置的Provider,还有.NET Core程序中使用User Secrets存储敏感数据这篇文章中使用的Microsoft.Extensions.Configuration.UserSecrets。
三、文件配置(以Json为例)
Json配置,需要安装Microsoft.Extensions.Configuration.Json包。
命令行下安装执行以下命令
dotnet add package Microsoft.Extensions.Configuration.Json -v 1.1.
调用AddJsonFile把Json配置的Provider添加到ConfigurationBuilder中。
class Program
{
public static IConfigurationRoot Configuration { get; set; } static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json"); Configuration = builder.Build();
}
}
如果使用Xml或Ini,只需安装相应的包,然后调用相应的扩展方法AddXmlFile("appsettings.xml)或AddIniFile("appsettings.ini")。
SetBasePath是指定从哪个目录开始查找appsettings.json。如果appsettings.json在configs目录中,那么调用AddJsonFile应该指定的路径为"configs/appsettings.json"。
下面是演示用的Json配置,后面会讲解所有读取它的方法
{
"AppId": "",
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"GrantTypes": [
{
"Name": "authorization_code"
},
{
"Name": "password"
},
{
"Name": "client_credentials"
}
]
}
(一)、读取JSON配置
1.使用Key读取
Configuration["AppId"]; // 结果 12345
Configuration["Logging:IncludeScopes"]; // 结果 false
Configuration["Logging:LogLevel:Default"]; // 结果 Debug
Configuration["GrantTypes:0:Name"]; // 结果 authorization_code
读取嵌套的配置,使用冒号隔开;读取数组形式的配置,使用数组的下标索引,0表示第一个。
如在其他地方用到Configuration的时候,可以通过构造函数注入IConfiguration。
首先配置IConfiguration的依赖
services.AddSingleton<IConfiguration>(Configuration);
然后在通过构造函数注入
private readonly IConfiguration _configuration;
public GetConfig(IConfiguration configuration)
{
_configuration = configuration;
}
2.使用GetValue<T>
这是一个扩展方法,使用它需要安装Microsoft.Extensions.Configuration.Binder包。
Configuration.GetValue<int>("AppId", ); // 结果 12345
Configuration.GetValue<bool>("Logging:IncludeScopes", false); // 结果 false
Configuration.GetValue<string>("Logging:LogLevel:Default", "Debug"); // 结果 Debug
Configuration.GetValue<string>("GrantTypes:0:Name", "authorize_code"); // 结果 authorization_code
GetValue方法的泛型形式有两个重载,一个是GetValue("key"),另一个可以指定默认值,GetValue("key",defaultValue)。如果key的配置不存在,第一种的结果为default(T),第二种的结果则为指定的默认值。
3.使用Options
这种方式需要安装Microsoft.Extensions.Options.ConfigurationExtensions包。
调用AddOptions()添加使用Options需要的服务。
services.AddOptions()
定义与配置对应的POCO类
public class MyOptions
{
public int AppId { get; set; } public LoggingOptions Logging { get; set; } public List<GrantType> GrantTypes { get; set; } public class GrantType
{
public string Name { get; set; }
}
} public class LoggingOptions
{
public bool IncludeScopes { get; set; } public LogLevelOptions LogLevel { get; set; }
} public class LogLevelOptions
{
public string Default { get; set; } public string System { get; set; } public string Microsoft { get; set; }
}
绑定整个配置到POCO对象上
services.Configure<MyOptions>(Configuration);
也可以绑定特定节点的配置
services.Configure<LoggingOptions>(Configuration.GetSection("Logging"));
或
services.Configure<LogLevelOptions>(Configuration.GetSection("Logging:LogLevel"));
在需要用到配置的地方,通过构造函数注入,或者直接使用ServiceProvider获取。
private readonly MyOptions _myOptions;
public GetConfig(IOptions<MyOptions> myOptionsAccessor)
{
_myOptions = myOptionsAccessor.Value;
}
或
var myOptionsAccessor = serviceProvider.GetService<IOptions<MyOptions>>();
var myOptions = myOptionsAccessor.Value;
4.使用Get<T>
Get<T>是.NET Core 1.1才引入的。
var myOptions = Configuration.Get<MyOptions>();
或
var loggingOptions = Configuration.GetSection("Logging").Get<LoggingOptions>();
5.使用Bind
和Get<T>类似,建议使用Get<T>。
var myOptions = new MyOptions();
Configuration.Bind(myOptions);
或
var loggingOptions = new LoggingOptions();
Configuration.GetSection("Logging").Bind(loggingOptions);
6、文件变化自动重新加载配置
IOptionsSnapshot支持配置文件变化自动重新加载配置。使用IOptionsSnapshot也很简单,AddJsonFile有个重载,指定reloadOnChange:true即可。
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("configs/appsettings.json", optional: false, reloadOnChange: true);
(二)、内存中配置
内存中配置调用AddInMemoryCollection(),其余和Json配置一样。
var dict = new Dictionary<string, string>
{
{"AppId",""},
{"Logging:IncludeScopes","false"},
{"Logging:LogLevel:Default","Debug"},
{"Logging:LogLevel:System","Information"},
{"Logging:LogLevel:Microsoft","Information"},
{"GrantTypes:0:Name","authorization_code"},
{"GrantTypes:1:Name","password"},
{"GrantTypes:2:Name","client_credentials"}
}; var builder = new ConfigurationBuilder()
.AddInMemoryCollection(dict);
或
var builder = new ConfigurationBuilder()
.AddInMemoryCollection(); Configuration["AppId"] = "";
(三)、命令行参数配置
命令行参数配置需要安装Microsoft.Extensions.Configuration.CommandLine包。
调用AddCommandLine()扩展方法将命令行配置Provider添加到ConfigurationBuilder中。
var builder = new ConfigurationBuilder()
.AddCommandLine(args);
传递参数有两种形式
dotnet run /AppId=
或
dotnet run --AppId
如果为--AppId提供一个缩写的参数-a,那么执行dotnet run -a 12345会报在switch mappings中没有-a定义的错误。
幸好AddCommandLine还有一个重载,可以传一个switch mapping。
var builder = new ConfigurationBuilder()
.AddCommandLine(args, new Dictionary<string, string>
{
{"-a","AppId"}
});
这样再运行下面的命令就不会报错了。
dotnet run -a
(四)、环境变量配置
环境变量配置需要安装Microsoft.Extensions.Configuration.EnvironmentVariables包。
调用AddEnvironmentVariables()扩展方法将环境变量配置Provider添加到ConfigurationBuilder中。
var builder = new ConfigurationBuilder()
.AddEnvironmentVariables();
获取所有的环境变量
Environment.GetEnvironmentVariables();
根据名称获取环境变量
Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
(五)、配置Provider顺序
.NET Core的配置API允许同时使用多个配置Provider。
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("configs/appsettings.json")
.AddXmlFile("configs/appsettings.xml")
.AddCommandLine(args)
.AddEnvironmentVariables();
如果两个Provider都有相同的配置,那么添加Provider的顺序就非常重要了,因为后加入的会覆盖前面的。
另外建议环境变量的配置Provider放到最后。
参考资料:https://www.cnblogs.com/nianming/p/7083964.html
Net core学习系列(九)——Net Core配置的更多相关文章
- 【.Net Core 学习系列】-- EF Core 实践(Code First)
一.开发环境: VS2015, .Net Core 1.0.0-preview2-003156 二解决方案: 新建项目: File --> New --> Project --> ...
- 【.Net Core 学习系列】-- EF Core实践(DB First)
一.开发环境: VS2015, .Net Core 1.0.0-preview2-003156 二.准备数据: CREATE DATABASE [Blogging]; GO USE [Blogging ...
- EntityFramework Core 学习系列(一)Creating Model
EntityFramework Core 学习系列(一)Creating Model Getting Started 使用Command Line 来添加 Package dotnet add pa ...
- 源码学习系列之SpringBoot自动配置(篇一)
源码学习系列之SpringBoot自动配置源码学习(篇一) ok,本博客尝试跟一下Springboot的自动配置源码,做一下笔记记录,自动配置是Springboot的一个很关键的特性,也容易被忽略的属 ...
- 源码学习系列之SpringBoot自动配置(篇二)
源码学习系列之SpringBoot自动配置(篇二)之HttpEncodingAutoConfiguration 源码分析 继上一篇博客源码学习系列之SpringBoot自动配置(篇一)之后,本博客继续 ...
- SpringBoot源码学习系列之SpringMVC自动配置
目录 1.ContentNegotiatingViewResolver 2.静态资源 3.自动注册 Converter, GenericConverter, and Formatter beans. ...
- SpringBoot源码学习系列之异常处理自动配置
SpringBoot源码学习系列之异常处理自动配置 1.源码学习 先给个SpringBoot中的异常例子,假如访问一个错误链接,让其返回404页面 在浏览器访问: 而在其它的客户端软件,比如postm ...
- ASP.NET Core学习系列
.NET Core ASP.NET Core ASP.NET Core学习之一 入门简介 ASP.NET Core学习之二 菜鸟踩坑 ASP.NET Core学习之三 NLog日志 ASP.NET C ...
- Net core学习系列(一)——Net Core介绍
一.什么是Net Core .NET Core是适用于 windows.linux 和 macos 操作系统的免费.开源托管的计算机软件框架,是微软开发的第一个官方版本,具有跨平台 (Windows. ...
随机推荐
- Java3-5年经验面试题总结
记录一下本次找工作所遇到的一些高频面试题,第一次找java工作,感觉比面试.net舒服多了,17年的时候出去找.net工作,由于在公司做的东西用到的技术少,除了mvc和ef,其他没啥问的,就追着项目问 ...
- 【转载】 C#中ArrayList集合类的使用
在C#的集合操作过程中,我们一般常用的集合类为List集合,List集合是一种强类型的泛型集合,其实还有一个ArrayList集合类,ArrayList集合类则非泛型类的集合,并且ArrayList集 ...
- 41、css总结
1.阴影:box-shadow:0 5px 20px rgba(0,0,0,.1); 2.css实现滚动进度条效果: body { position: relative; padding: 50p ...
- FreePascal - CodeTyphon 如何调整代码编辑器背景色?
当前版本的CodeTyphon默认背景色是黑色,看起来很不习惯,通过下面操作,修改了它的代码编辑器的背景色: 1,打开CodeTyphon的菜单“工具”->“选项”. 2,选择左侧列表项目“颜色 ...
- 基于Chrominum的发行版本Microsoft Edge-Beta
问题描述: Microsoft Edge -->Chromium Edge(未来Window的主力浏览器) 问题解决: 下载地址: https://www.microsoftedgeinside ...
- Redis SCAN命令实现有限保证的原理
SCAN命令可以为用户保证:从完整遍历开始直到完整遍历结束期间,一直存在于数据集内的所有元素都会被完整遍历返回,但是同一个元素可能会被返回多次.如果一个元素是在迭代过程中被添加到数据集的,又或者是在迭 ...
- Flask基础之返回值与form表单提交
目录 1.Python 现阶段三大主流Web框架 Django Tornado Flask 对比 2.Flask的安装 3.Flask的第一个简单应用 4.Flask中的render_template ...
- C#实体类与XML相互转换
1.实体类与XML相互转换 将实体类转换成XML需要使用XmlSerializer类的Serialize方法,将实体类序列化. 把XML转换成相应的实体类,需要使用到XmlSerializer类的De ...
- CentOS7 编译安装MySQL5.6.38(一)
一.下载MySQL5.6.38安装包 下载地址:https://www.mysql.com/downloads/ 打开网站之后选择Archives 然后再选择开源版本 选择我们要下载的版本: htt ...
- Android开发学习了这些,上帝都淘汰不了你
曾听过很多人说Android学习很简单,做个App就上手了,工作机会多,毕业后也比较容易找工作.这种观点可能是很多Android开发者最开始入行的原因之一. 在工作初期,工作主要是按照业务需求实现Ap ...