一、简介

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配置的更多相关文章

  1. 【.Net Core 学习系列】-- EF Core 实践(Code First)

    一.开发环境: VS2015, .Net Core 1.0.0-preview2-003156 二解决方案: 新建项目: File --> New --> Project -->   ...

  2. 【.Net Core 学习系列】-- EF Core实践(DB First)

    一.开发环境: VS2015, .Net Core 1.0.0-preview2-003156 二.准备数据: CREATE DATABASE [Blogging]; GO USE [Blogging ...

  3. EntityFramework Core 学习系列(一)Creating Model

    EntityFramework Core 学习系列(一)Creating Model Getting Started 使用Command Line 来添加 Package  dotnet add pa ...

  4. 源码学习系列之SpringBoot自动配置(篇一)

    源码学习系列之SpringBoot自动配置源码学习(篇一) ok,本博客尝试跟一下Springboot的自动配置源码,做一下笔记记录,自动配置是Springboot的一个很关键的特性,也容易被忽略的属 ...

  5. 源码学习系列之SpringBoot自动配置(篇二)

    源码学习系列之SpringBoot自动配置(篇二)之HttpEncodingAutoConfiguration 源码分析 继上一篇博客源码学习系列之SpringBoot自动配置(篇一)之后,本博客继续 ...

  6. SpringBoot源码学习系列之SpringMVC自动配置

    目录 1.ContentNegotiatingViewResolver 2.静态资源 3.自动注册 Converter, GenericConverter, and Formatter beans. ...

  7. SpringBoot源码学习系列之异常处理自动配置

    SpringBoot源码学习系列之异常处理自动配置 1.源码学习 先给个SpringBoot中的异常例子,假如访问一个错误链接,让其返回404页面 在浏览器访问: 而在其它的客户端软件,比如postm ...

  8. ASP.NET Core学习系列

    .NET Core ASP.NET Core ASP.NET Core学习之一 入门简介 ASP.NET Core学习之二 菜鸟踩坑 ASP.NET Core学习之三 NLog日志 ASP.NET C ...

  9. Net core学习系列(一)——Net Core介绍

    一.什么是Net Core .NET Core是适用于 windows.linux 和 macos 操作系统的免费.开源托管的计算机软件框架,是微软开发的第一个官方版本,具有跨平台 (Windows. ...

随机推荐

  1. Kafka Streams开发入门(4)

    背景 上一篇演示了filter操作算子的用法.今天展示一下如何根据不同的条件谓词(Predicate)将一个消息流实时地进行分流,划分成多个新的消息流,即所谓的流split.有的时候我们想要对消息流中 ...

  2. Nmon监控性能分析

    一.CPU信息 1.折线图中蓝线为cpu占有率变化情况:粉线为磁盘IO的变化情况: 2.下面表各种左边的位磁盘的总体数据,包括如下几个: Avg tps during an interval 每个间隔 ...

  3. .Net core 使用swagger进行Api管理

    上次我们讲过如何在swagger上隐藏接口,众所周知,swagger是一个强大的api文档工具,可以帮助我们记录文档并且测试接口,也是一个可视化操作接口的工具. 那么如果我们写的接口非常多的时候怎么办 ...

  4. Django rest framework 之版本

    一.通过 QueryParameterVersioning 获取版本 通过 QueryParameterVersioning 从 get 请求中获取版本信息: 1.新建 app,名为 api,Proj ...

  5. 数据科学:pd.DataFrame.drop()

    一.功能 删除集合中的整行或整列: 二.格式 df.drop(labels=None, axis=0, index=None, columns=None, level=None, inplace=Fa ...

  6. free - 显示系统内存信息

    free - Display amount of free and used memory in the system 显示系统中空闲和已使用内存的数量 格式: free [options] opti ...

  7. 使用MPU6050陀螺仪自制Arduino数字量角器

    MPU6050惯性单元是一个3轴加速度计和一个3轴陀螺仪组合的单元.它还包含温度传感器和DCM,可执行复杂的任务. MPU6050通常用于制作无人机和其他远程控制机器人,如自平衡机器人.在本篇文章中, ...

  8. version GLIBCXX_3.4.21 not defined in file libstdc++.so.6 with link time reference

    在python中运行如下: $ python >>> import wx 输出:symbol _ZNSt7__cxx1112basic_stringIwSt11char_traits ...

  9. C# 中静态调用C++dll 和C# 中动态调用C++dll

    在最近的项目中,牵涉到项目源代码保密问题,由于代码是C#写的,容易被反编译,因此决定抽取核心算法部分使用C++编写,C++到目前为止好像还不能被很好的反编译,当然如果你是反汇编高手的话,也许还是有可能 ...

  10. 【VUE】图片预览放大缩小插件

    From: https://www.jianshu.com/p/e3350aa1b0d0 在看项目时,突然看到预览图片的弹窗,感觉好僵硬,不能放大,不能切换,于是便在网上找下关于图片预览的插件,有找到 ...