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. ...
随机推荐
- redis AbortOnConnectFail
AbortOnConnectFail =true 服务器上停止redis service,即便后来redis服务端修好能够接通时,也不会自动连接. 所以建议设为false
- js设置全局变量与读取全局变量
方法1: 设置: var a = 1; 读取: a window.a window['a'] 方法2: 设置: window.b=2; 读取: b window.b window['b'] 方法3: ...
- Django:RestFramework之-------版本控制
6.版本控制 从URL通过get传参获取版本. 6.1自定义版本控制 from rest_framework.views import APIView class ParamVersion(objec ...
- 英语rubyspinel红尖晶石rubyspinel单词
红尖晶石(rubyspinel或Red spinel)其红色是因含铬而致^像红宝石和红色石榴子石一样,红 尖晶石也曾被叫作红玉,这就造成了红色宝石的混乱,因为世界上一些最大的著名“红宝 石”,如英国王 ...
- SAP CDS redirect view支持写操作吗,一个实验来验证
According to this wiki, write back on CDS view is not supported: And also it is defined in ABAP help ...
- Golang Web应用 创建docker镜像笔记(win 平台)
记录的是 本地编译好了再创建容器镜像的方法 ,这样子生成的镜像文件比较小,方便分发部署 win 平台需要设置golang交叉编译 生成linux可执行文件 CMD下: Set GOOS="l ...
- centos 7 新机器安装部署配置
首先卸载openjdk,安装jdk 1.查看java版本 [lambert@localhost ~]$ java -version openjdk version "1.8.0_102&qu ...
- Backbone——数据驱动UI的js开发模式
转载请注明原文地址:https://www.cnblogs.com/ygj0930/p/10826074.html 一:Backbone是什么——JS的MVC框架 Backbone基于undersco ...
- Beta冲刺第4次
二.Scrum部分 1. 各成员情况 翟仕佶 学号:201731103226 今日进展 今天不再使用Excel绘制燃尽图,改学习使用highcharts绘制 存在问题 对前端不够了解,第一次在这博客园 ...
- 项目Beta冲刺(6/7)(追光的人)(2019.5.28)
所属课程 软件工程1916 作业要求 Beta冲刺博客汇总 团队名称 追光的人 作业目标 描述Beta冲刺每日的scrum和PM报告两部分 队员学号 队员博客 221600219 小墨 https:/ ...