创建 ConfigHelper 类
---------注意事项:在测试的时候如果使用的是
IConfiguration configuration = new ConfigurationBuilder().SetBasePath(AppContext.BaseDirectory).AddJsonFile(“appsettings.json”).Build()
public class ConfigHelper
{
public static IConfiguration config;
///获取一级数据
public static string GetValue(string key)
{
return config.GetSection(key).Value;
}
///获取实体
public static T GetConfig<T>(string key) where T : class, new()
{
var data = new ServiceCollection()
.AddOptions()
.Configure<T>(config.GetSection(key))
.BuildServiceProvider()
.GetService<IOptions<T>>()
.Value;
return data;
}
获取ConnectionStrings 下key节点下数据
public static string GetConnStrValue(string key)
{
return config[$"ConnectionStrings:{key}"];
}
appsettings.json
{
"Data": "LineZero",
"ConnectionStrings": {
"DefaultConnection": "server=test.anssy.com;database=YiqiJiankong485;uid=user;pwd=pwd;",
"DevConnection": "数据库2"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
在 start操作的时候获取的节点下数据的方法
//var data = Configuration["Data"];
两种方式读取
//var defaultcon = Configuration.GetConnectionString("DefaultConnection");
//var devcon = Configuration["ConnectionStrings:DevConnection"];
另外的配置方式
读取Json文件 1. 准备数据
首先准备一个Json文件,如下所示:
{ "Name": "Alan.hsiang", "Age": 20, "Sex": "male", "Like": ["basketball","football","swimming"], "Score": { "LandLit": 90, "Mathematics": 99, "English": 50 }}
`IConfiguration configuration = new ConfigurationBuilder().SetBasePath(Environment.CurrentDirectory).AddJsonFile("student.json").Build();`
var name = configuration["Name"]; //IConfiguration接口自带的索引器,只返回字符串类型。如:名字2
var like0 = configuration["Like:0"];//读取数组中第一个元素 如:第一个爱好3
var like2 = configuration["Like:2"];//读取数组中第三个元素 如:第三个爱好4
var landLit = configuration["Score:LandLit"];//获取字节点的属性值,如:语文成绩
注意:如果Json数据有层级关系,则通过冒号【:】进行表示。
var age = configuration.GetValue<int>("Age");//获取其他数据类型,如:int,如:年龄
//获取整个数组,如:爱好2
var like = new List<string>();3 configuration.Bind("Like",like);
首先复制整个Json文件的内容,然后依次点击【编辑–>选择性粘贴–>将JSON粘贴为类】菜单,如下所示:
默认生成的类名为RootObject,然后修改为Student,具体如下所示:
namespace DemoCore
{
public class Student
{ public string Name { get; set; }
public int Age { get; set; }
public string Sex { get; set; }
public string[] Like { get; set; }
public Score Score { get; set; }
}
public class Score
{
public int LandLit { get; set; }
public int Mathematics { get; set; }
public int English { get; set; }
}
}
将Student类和配置对象进行绑定,如下所示:
1 //2. 复杂读取
var student = new Student();
configuration.Bind(student);
Console.WriteLine($"name={student.Name},age={student.Age},like= {string.Join(",", student.Like)},score={student.Score.English}");
学习方法:
https://blog.csdn.net/cmdos/article/details/123308982