1. 特性
- 支持将配置值绑定到已有对象
- 支持将配置值绑定到私有属性上
2. 安装包
Microsoft.Extensions.Configuration.Binder
3. 常规用法
public static void Main(string[] args)
{
var build = new ConfigurationBuilder();
//optional=false,文件不存在的时候会报错,reloadOnChange=true文件发生变化时重新读取
build.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
var config = build.Build();
Config con = new Config()
{
AllowedHosts = ""
};
config.Bind(con);
Console.WriteLine($"AllowedHosts:{con.AllowedHosts}");
Console.ReadKey();
CreateHostBuilder(args).Build().Run();
}
4. 配置文件嵌套格式用法
public static void Main(string[] args)
{
var build = new ConfigurationBuilder();
//optional=false,文件不存在的时候会报错,reloadOnChange=true文件发生变化时重新读取
build.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
var config = build.Build();
Config con = new Config()
{
AllowedHosts = "",
Ip = "192.168.0.1",
Port = 3306,
Db = 6
};
config.GetSection("Redis").Bind(con);
Console.WriteLine($"AllowedHosts:{con.AllowedHosts}");
Console.WriteLine($"Ip:{con.Ip}");
Console.WriteLine($"Port:{con.Port}");
Console.WriteLine($"Db:{con.Db}");
Console.ReadKey();
CreateHostBuilder(args).Build().Run();
}
5. 配置值绑定到私有属性
public static void Main(string[] args)
{
var build = new ConfigurationBuilder();
//optional=false,文件不存在的时候会报错,reloadOnChange=true文件发生变化时重新读取
build.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
var config = build.Build();
Config con = new Config()
{
AllowedHosts = "",
Ip = "192.168.0.1",
Port = 3306,
Db = 6
};
config.GetSection("Redis").Bind(con,
binderOptions => { binderOptions.BindNonPublicProperties = true; });
Console.WriteLine($"AllowedHosts:{con.AllowedHosts}");
Console.WriteLine($"Ip:{con.Ip}");
Console.WriteLine($"Port:{con.Port}");
Console.WriteLine($"Db:{con.Db}");
Console.WriteLine($"Name:{con.Name}");
Console.ReadKey();
CreateHostBuilder(args).Build().Run();
}
6. 配置文件内容
"AllowedHosts": "*",
"Redis": {
"IP": "127.0.0.1",
"Port": 3306,
"Db": 0
}
7. 配置实体类代码
public class Config
{
public string AllowedHosts { get; set; }
public string Ip { get; set; }
public int Port { get; set; }
public int Db { get; set; }
public string Name { get; private set; } = "张三";
}