.net core 使用强类型对象承载配置数据 电脑版发表于:2020/6/28 15:45 ![.netcore](https://img.tnblog.net/arcimg/hb/c857299a86d84ee7b26d181a31e58234.jpg ".netcore") >#.net core 使用强类型对象承载配置数据 [TOC] <br/> 要点 ------------ <br/> - 支持将配置值绑定到已有对象 - 支持将配置值绑定到私有的属性上 <br/> 简单示例 ------------ <br/> >###项目结构 <br/> >内容请参考:https://www.tnblog.net/hb/article/details/4140 <br/> >###附加新的包 - Microsoft.Extensions.Configuration.Binder <br/> >###修改内容 <br/> ><font style="color:#f1c40f;font-weight:bold;">appsetting.json</font> ```json { "Key1": "Value1", "Key2": "Value2", "Key5": false, "Key6": 0 } ``` ><font style="color:#2ecc71;font-weight:bold;">Program.cs</font> ```csharp static void Main(string[] args) { var builder = new ConfigurationBuilder(); builder.AddJsonFile("appsetting.json",optional:false,reloadOnChange:true); var configurationRoot = builder.Build(); var config = new Config() { Key1="config Key1", Key5=false, Key6=1000 }; configurationRoot.Bind(config); Console.WriteLine($"Key1:{config.Key1}"); Console.WriteLine($"Key5:{config.Key5}"); Console.WriteLine($"Key6:{config.Key6}"); Console.ReadKey(); } class Config { public string Key1 { get; set; } public bool Key5 { get; set; } public int Key6 { get; set; } } ``` >运行结果 ![运行结果](https://img.tnblog.net/arcimg/hb/bb56226b028b40b6a61375f83daaf99d.png) >我们发现配置数据发生了一些改变 <br/> >###修改部分代码运行 <br/> >修改<font style="color:#f1c40f;font-weight:bold;">appsetting.json</font>配置 ```json { "Key1": "Value1", "Key2": "Value2", "Key5": false, "Key6": 0, "OrderService": { "Key1": "Order key5", "Key5": true, "Key6": 200 } } ``` ><font style="color:#2ecc71;font-weight:bold;">Program.cs</font> ```csharp static void Main(string[] args) { var builder = new ConfigurationBuilder(); builder.AddJsonFile("appsetting.json",optional:false,reloadOnChange:true); var configurationRoot = builder.Build(); var config = new Config() { Key1="config Key1", Key5=false, Key6=1000 }; configurationRoot.GetSection("OrderService").Bind(config); Console.WriteLine($"Key1:{config.Key1}"); Console.WriteLine($"Key5:{config.Key5}"); Console.WriteLine($"Key6:{config.Key6}"); Console.ReadKey(); } ``` >运行结果 ![运行结果](https://img.tnblog.net/arcimg/hb/1776b8261f5a417eb6ac39b3204e203a.png) >我们发现并没有发生变化 <br/> >设置属性,私有字段赋值 ```csharp configurationRoot.GetSection("OrderService").Bind(config,binderOptions=> { binderOptions.BindNonPublicProperties = true; }); ``` >再次运行 ![再次运行](https://img.tnblog.net/arcimg/hb/46188b4d728f4482aed86d1daddfe73f.png)