1 .Net Core 中的配置文件介绍
1.1 简单回顾. Net Framework 配置文件
.Net Core 中的配置文件操作较. Net Framework 有了很大的改动. 介绍. Net Core 中配置文件操作前, 我们先回顾下. Net Framework 中配置文件的操作. 在. Net Framework 中应用程序的配置文件只支持 xml 形式, 应用程序的配置文件一般是 App.Config 或者 web.Config, 添加配置文件最常用的方法是: 在 appSettings 和 ConnectionString 节点下添加子节点, 简单看一个栗子
配置文件下添加子节点:
- <appSettings>
- <add key="mykey" value="myvalue"/>
- </appSettings>
- <connectionStrings>
- <add name="connstr" connectionString="server=.;uid=sa;pwd=xxxx;database=mydbname"/>
- </connectionStrings>
获取配置文件中的值:
//MVC 中读取配置文件 ViewBag.value = WebConfigurationManager.AppSettings["mykey"]; ViewBag.connstr = WebConfigurationManager.ConnectionStrings["connstr"].ConnectionString; //Webapi,Console,Winform 应用读取配置文件 string s1 = ConfigurationManager.AppSettings["mykey"]; string s2 = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
.Net Core 的配置文件相比于. Net Framework 最大的特点是其不仅仅支持 xml 格式的配置文件, 还支持 JSON,INI,memory,command,env(环境变量). 首先看一个 JSON 配置文件的栗子.
1.2 JSON 配置文件的操作
这里采用一个控制台项目作为栗子, ASP.NET Core 中配置文件的操作基本一致. 首先添加两个包
Install-Package Microsoft.Extensions.Configuration Install-Package Microsoft.Extensions.Configuration.JSON
添加配置文件, 文件名可以任意指定, 这里使用 appsettings.JSON, 设置属性为[始终复制]
{ "isRight": true, "myArray": [ 10, 20, 30, 40 ], "myJson": { "key1": "json 中的 value1", "key2": "json 中的 value2" } }
读取配置文件中数据, 代码如下:
class Program { static void Main(string[] args) { IConfiguration configuration = new ConfigurationBuilder() // 设置配置文件基本路径 .SetBasePath(Environment.CurrentDirectory) // 添加 JSON 配置. 参数: optional 配置文件是否为可选的, reloadOnChange 是否热加载 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .Build(); Console.WriteLine(configuration["isRight"]); Console.WriteLine(configuration["myArray:0"]);// 输出 myArray[0], [:] 表示下一级节点 Console.WriteLine(configuration["myJson:key1"]);// 输出 myJson->key1 [:] 表示下一级节点 Console.ReadKey(); } }
在. Net Core 中使用 ConfigurationBuilder 对象的 SetBasePath(strPath) 设置配置文件的基本路径, AddJsonFile("filePath") 方法添加配置文件, Build 方法创建配置对象.
运行结果为
1.3 其他类型的配置文件
上边提到. Net Core 的配置文件支持多种类型, Configuration 的数据源可以来自 JSON,xml, 环境变量, INI,Memory 等, 下边我们看一下怎么去操作其他类型配置文件.
首先添加几个 Package
//xml 配置文件 Install-Package Microsoft.Extensions.Configuration.xml //INI 配置文件 Install-Package Microsoft.Extensions.Configuration.INI // 环境变量 Install-Package Microsoft.Extensions.Configuration.EnvironmentVariables // 支持强类型读取, 扩展了 IConfiguration 的方法 Install-Package Microsoft.Extensions.Configuration.Binder
添加 xml 配置文件, 文件名为 appsettings.xml, 属性设置为[始终复制]
<appsettings> <mykey>myvalue</mykey> <MySQL> <server>192.168.11.11</server> <port>3306</port> </MySQL> </appsettings>
一个简单的栗子
class Program { static void Main(string[] args) { //memory 配置数据 var initData = new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>("initKey1", "初始配置数据 1"), new KeyValuePair<string, string>("initKey2", "初始配置数据 2"), }; IConfiguration configuration = new ConfigurationBuilder() // 设置根目录 .SetBasePath(Environment.CurrentDirectory) // 添加 JSON 配置. 参数: optional 配置文件是否为可选的, reloadOnChange 是否热加载 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) // 添加 xml 文件配置 .AddXmlFile("appsettings.xml") // 添加 memory 中的配置 .AddInMemoryCollection(initData) // 将环境变量添加到配置 .AddEnvironmentVariables() .Build(); // 方式 1: 弱类型读取 string str1 = configuration["initKey1"]; string str2 = configuration["isRight"]; string str3 = configuration["myArray:0"]; string str4 = configuration["myJson:key1"]; // 我电脑上配置的 NPM_HOME 环境变量 string str5 = configuration["NPM_HOME"]; string str6 = configuration["mysql:server"]; Console.WriteLine($"{str1}--{str2}--{str3}--{str4}--{str5}--{str6}"); // 方式 2: 强类型 //Microsoft.Extensions.Configuration.Binder 扩展了 Configuration 的方法 string strA = configuration.GetValue<string>("initKey1"); bool boolB = configuration.GetValue<bool>("isRight"); int intC = configuration.GetValue<int>("myArray:0"); string strD = configuration.GetValue<string>("myJson:key1"); // 我电脑上配置的 NPM_HOME 环境变量 string strE = configuration.GetValue<string>("NPM_HOME"); string strF = configuration.GetValue<string>("mysql:server"); Console.WriteLine($"{strA}--{boolB}--{intC}--{strD}--{strE}--{strF}"); Console.ReadKey(); } } View Code
运行结果
我们看一下 Configuration 对象是怎么存储配置的, 每一个配置源的数据都单独存放在一个 Provider 中, 存储的方式如下图所示, 无论是 JSON/xml 还是其他类型的配置源, 配置最终都以 Key-Value 的形式存储在所对应的 Provider 中.
一点重要的补充: 如果多个配置文件中都配置了同一个 Key 值, 那么以后面添加的准. 如先添加 xml 配置文件, 然后添加 JSON 配置文件, JSON 配置文件会覆盖 xml 配置文件中重复的配置.
1.4 通过对象方式读取配置文件
通过上边的介绍我们已经知道怎么去添加和读取配置文件, 但是读取时都是用 Key 来获取 Configuraion 对象中的值 (), 如果能以对象的形式(如 configuration.mykey) 来读取 configuration 就会更方便了. Microsoft.Extensions.Configuration.Binder 包为我们提供了这种方法. 以 JSON 配置文件为例, 配置文件 appsettings 的内容如下:
{ "isRight": true, "myArray": [ 10, 20, 30, 40 ], "myJson": { "key1": "json 中的 value1", "key2": "json 中的 value2" } }
生成 configuration 绑定的类, 可以自己写一个绑定类.(一个小技巧: 复制 appsettings 中的内容,[编辑] -[选择性粘贴] -[将 JSON 粘贴为类] )
效果如下:
具体操作的代码如下
class Program { static void Main(string[] args) { IConfiguration configuration = new ConfigurationBuilder() // 设置根目录 .SetBasePath(Environment.CurrentDirectory) // 添加 JSON 配置. 参数: optional 配置文件是否为可选的, reloadOnChange 是否热加载 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .Build(); // 普通方式读取 Console.WriteLine("---------------- 普通方式读取"); Console.WriteLine($"{configuration["isRight"]}--{configuration["myArray:0"]}--{configuration["myJson:key1"]}"); // 对象方式读取 Rootobject cfgObj = configuration.Get<Rootobject>(); // 也可以用下边的方式绑定, 效果一样: //Rootobject cfgObj = new Rootobject(); //configuration.Bind(cfgObj); Console.WriteLine("---------------- 对象方式读取"); Console.WriteLine($"{cfgObj.isRight}--{cfgObj.myArray[0]}--{cfgObj.myJson.key1}"); Console.ReadKey(); } } // 绑定 Configuration 对象的类 public class Rootobject { public bool isRight { get; set; } public int[] myArray { get; set; } public Myjson myJson { get; set; } } public class Myjson { public string key1 { get; set; } public string key2 { get; set; } }
通过对象绑定读配置文件有两个优点:1读取配置文件时为强类型读取(如 configuration.isRight 为 bool 类型, 而不是同一的 string 类型),2具有代码提示功能
来源: http://www.bubuko.com/infodetail-2968210.html