Skip to content

读取 JSON 配置文件

安装读取 json文件的 Nuget 包:

shell
Install-Package Microsoft.Extensions.Configuration
Install-Package Microsoft.Extensions.Configuration.Json

项目中新建 appsetting.json 文件,并将其属性中的【复制到输出目录】设置为 “如果较新则复制”;

json
{
  "name": "sunny",
  "proxy": {
    "address": "127.0.0.1",
    "port": "8500"
  }
}

在 Program.cs 中注入 appsetting.json 文件:

C#
var configBuilder = new ConfigurationBuilder();
configBuilder.AddJsonFile("appsetting.json", true, false);
var configuration = configBuilder.Build();

AddJsonFile(path, optional, reloadOnChange) 方法的参数:

参数说明
path配置文件路径
optionaltrue 表示配置文件不存在时不报错,false 则表示会报错
reloadOnChange配置文件修改了,是否重新加载配置

GetSection

GetSection() 用于获取某个部分节点(如:proxy 整个节点)或单个节点(如:name 节点)。

C#
// 获取 proxy 整个节点
IConfigurationSection? proxy = configuration.GetSection("proxy");
string? name = proxy["address"];
string? port = proxy["port"];
// 直接获取单个节点值
string? name = configuration.GetSection("name").Value;
string? address = configuration.GetSection("proxy:address").Value;
string? port = configuration.GetSection("proxy:port").Value;

GetValue

GetValue() 用于获取配置文件中的单一值(如字符串、整数、布尔值等),和 GetSection() 获取单节点值相同。

C#
string? name = configuration.GetValue<string>("name");
string? address = configuration.GetValue<string>("proxy:address");
int port = configuration.GetValue<int>("proxy:port");

Get

Get() 用于绑定配置文件中的某个部分到一个强类型对象。

shell
# 安装 Nuget 包
Install-Package Microsoft.Extensions.Configuration.Binder
C#
class Config
{
  public string? Name { get; set; }
  public Proxy? Proxy { get; set; }
}

class Proxy
{
  public string? Address { get; set; }
  public string? Port { get; set; }
}
C#
// 读取 Proxy 对应的内容
Proxy? proxy = configuration.GetSection("proxy").Get<Proxy>();
string? address = proxy?.Address;
string? port = proxy?.Port

// 读取 Config 对应的内容
Config? config = configuration.Get<Config>();
string? name = config?.Name;
string? address = config?.Proxy?.Address;
string? port = config?.Proxy?.Port;

Released under the MIT License.