.Net中的配置系统支持丰富的配置源,包括文件(json、xml、ini等)、注册表、环境变量、命令行、azure key vault等,还可以配置自定义配置源。可以跟踪配置的改变,可以按照优先级覆盖。
传统项目一般是从web.config文件中读取配置项的值,配置项一般是xml格式。如下图所示:
这种配置方式有一个弊端,当配置项比较复杂时,比如有多个层级,一层层嵌套,看起来非常不直观。这时候用json格式的配置就显得很方便。下面用代码示例展示json格式配置文件的基本用法(代码基于.NetCore3.1版本):
方法一:
1.创建一个json文件,文件名称随意(例如:config.json),设置文件属性为“如果较新则复制”。
2.nuget安装:Microsoft.Extensions.Configuration和Microsoft.Extensions.Configuration.Json;
3.代码示例:
static void Main(string[] args)
{
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonFile("config.json", optional: true, reloadOnChange: true);
IConfigurationRoot root = configurationBuilder.Build();
string name = root["name"];
Console.WriteLine($"name={name}");
string address = root.GetSection("proxy:address").Value;
Console.WriteLine($"address={address}");
Console.ReadLine();
}
执行结果:
如果读取根节点的配置项,比如name,直接root["name"]就可以。
如果读取子节点的配置项,比如proxy节点下的address,则需要调用GetSection方法,中间的参数名称用冒号(:)连接,表示子节点,root.GetSection("proxy:address").Value
如果有多级子节点,一直用冒号连接,直到最内层节点为止,比如要获取到addr1的值
string address = root.GetSection("proxy:address:addr1").Value;
方法二:
除了根据节点的名称读取外,还可以将json配置文件的信息映射为class类,通过常规的(.)点调用,获取到配置项的值:
1.nuget安装:Microsoft.Extensions.Configuration.Binder;
2.代码示例:
static void Main(string[] args)
{
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonFile("config.json", optional: true, reloadOnChange: true);
IConfigurationRoot root = configurationBuilder.Build();
ConfigJson config = root.Get<ConfigJson>();//将json配置项映射为一个对象
Console.WriteLine(config.name);
Console.WriteLine(config.proxy.port);
Console.ReadLine();
}
自定义类,类中的字段名称跟json配置项名称对应:
class ConfigJson
{
public string name { get; set; }
public string age { get; set; }
public Proxy proxy { get; set; }
}
class Proxy
{
public string address { get; set; }
public int port { get; set; }
}
执行结果:
这种方法跟第一种的区别是,这里使用IConfigurationRoot.Get方法,将json配置项映射为一个对象。
以上两种方法在实际的开发中,并不会这么写,因为比较麻烦,但这是基础用法,下面文章会对上面的基础写法封装,更方便在实际开发中使用。