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. ...
随机推荐
- vue-awesome-swiper兼容ie9
轮播插件vue-awesome-swiper在ie9中运行的时候没效果 解决方法: vue-awesome-swiper在IE9下报错, 主要原因是element.classlist.add()方法在 ...
- word,excel,ppt转pdf
第一步 需要下载jar包和jacob-1.14.3-x64.dll * <dependency> * <groupId>net.sf.jacob-project</gro ...
- APS应用案例|纽威阀门实现高效排产
企业背景: 苏州纽威阀门股份有限公司(下文简称:纽威阀门)成立于1997年,总部设在江苏苏州.自成立以来一直致力于工业阀门的研发与制造,以为客户提供全套工业阀门解决方案为目标.纽威阀门通过企业的努力发 ...
- XmlDocument.load 读文件报异常:文件正被其它线程使用,解决方法
string filePath = Form1.getProjectFilePath(); System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocu ...
- linux常见依赖
1. 搭建LNMP环境用到的依赖包 yum -y install gcc gcc-c++ libxml2 libxml2-devel openssl openssl-devel curl libcur ...
- AWS 存储过程
DELIMITER $$ USE `mysql`$$ DROP PROCEDURE IF EXISTS `rds_rotate_slow_log`$$ CREATE DEFINER=`rdsadmin ...
- YUV和RGB格式单像素所占内存大小分析
图片的大小定 义为:w * h,宽高分别为w和h 一.YUV格式 1.1.YUV420格式存储方式:先Y,后V,中间是U.其中的Y是w * h,U和V是w/2 * (h/2)举例:如果w = 4,h ...
- spring mvc @RequestMapping method 不写的话,默认GET、POST都支持,根据前端方式自动适应
@RequestMapping(value="/") method 不写的话,默认GET.POST都支持,根据前端方式自动适应.
- 20180530模拟赛T2——绀碧之棺
题目背景 qiancl 得到了一张藏宝图,上面写了一道谜题. 题目描述 定义\(F(n)\)为 n 在十进制下各个数位的平方和,求区间\([a,b]\)中有多少\(n\)满足\(k\times F(n ...
- Windows GUI自动化测试技术的比较和展望
https://www.cnblogs.com/yufun/archive/2009/10/10/1580132.html [这里的自动化测试专指GUI自动化(不包含Web)] 以前写过一篇跟UI自动 ...