NuGet包:
Microsoft.Extensions.Configuration.Binder(将读取到的配置文件转换成指定类型)
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.Environment(可读取环境变量,系统变量)
Microsoft.Extensions.Configuration.FileExtensions(查找配置文件位置)
Microsoft.Extensions.Configuration.Json(添加 配置源文件操作)
测试所用配置文件:
{ "classValue": { "firstValue": "first get config value", "secondValue": "second get config value" }, "singleValue": "single", "arrayValue": [ { "firstValue": "first class one", "secondValue": "first class two" }, { "firstValue": "second class one", "secondValue": "second class two" } ] }
代码:
1. 创建ConfigurationBuilder对象
public IConfigurationRoot ConfigBuild() { var config = new ConfigurationBuilder(); //设置文件路径,配置热加载(当文件改变时,重新加载)*********************** config.SetBasePath(Directory.GetCurrentDirectory().ToString()).Add(new JsonConfigurationSource { Path = "appSetting.json", ReloadOnChange = true }); //不热加载 //config.SetBasePath(Directory.GetCurrentDirectory().ToString()).AddJsonFile("appSetting.json"); //可读取环境变量,系统变量(提供重载 prefix,会筛选出符合前缀名的环境/系统变量) ****************************** //config.AddEnvironmentVariables(); config.AddEnvironmentVariables("test"); return config.Build(); }
2.读取配置文件
包含了JSON中常见的键值格式。单个值,类,数组
NetCoreReadConfig netCoreReadConfig = new NetCoreReadConfig(); //读取类 //ConfigTestClass testConfigValue = netCoreReadConfig.ConfigBuild().GetSection("classValue").Get<ConfigTestClass>(); // ****************** //var signleConfig = netCoreReadConfig.ConfigBuild()["classValue:firstValue"]; //Console.WriteLine(testConfigValue.firstValue); //Console.WriteLine(testConfigValue.secondValue); //读取单个值 var signleConfig = netCoreReadConfig.ConfigBuild()["singleValue"]; Console.WriteLine(signleConfig); //读取环境变量、系统变量 //Environment.SetEnvironmentVariable("codeAddOsConfig","codeAdd"); //var osEnvironmentConfig = netCoreReadConfig.ConfigBuild().GetSection("ASPNETCORE_ENVIRONMENT").Value; //var osEnvironmentConfig = netCoreReadConfig.ConfigBuild().GetSection("codeAddOsConfig").Value; //Console.WriteLine(osEnvironmentConfig); //读取数组 ConfigTestClass[] arrayConfig; arrayConfig = netCoreReadConfig.ConfigBuild().GetSection("arrayValue").Get<ConfigTestClass[]>(); foreach (var item in arrayConfig) { Console.WriteLine(item.firstValue); } Console.ReadKey();
另外补充
1.因为 IConfigurationRoot 继承自 IConfiguration,所以使用 GetSection("") 或 [""] 都可以
2.系统环境变量查看:控制面板->系统高级设置 | <变量的优先等级博主未测试> | <博主尝试手动添加系统/用户变量,重启后才生效,大家如果有什么提示可以评论补充>
环境变量 | <这个是立即生效的>