随笔 - 165, 文章 - 0, 评论 - 18, 阅读 - 22万
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

.net core 基础之读取配置文件

Posted on   火冰·瓶  阅读(196)  评论(0编辑  收藏  举报

一、通过nuget安装扩展包

需要安装如下扩展包

Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.Binder
Microsoft.Extensions.Configuration.Json

 二、在启动项目中新建json文件

复制代码
{
  "Name": "Alan.hsiang",
  "Age": 20,
  "Sex": "male",
  "Like": [ "basketball", "football", "swimming" ],
  "Score": {
    "LandLit": 90,
    "Mathematics": 99,
    "English": 50
  }
}
复制代码

三、创建IConfiguration接口实例,通过索引器读取配置文件

//IConfiguration configuration = new ConfigurationBuilder().SetBasePath(Environment.CurrentDirectory).AddJsonFile("tsconfig.json").Build();  //可以指定路径
IConfiguration configuration = new ConfigurationBuilder().AddJsonFile("tsconfig.json",true,true).Build();
var name = configuration["Name"]; //IConfiguration接口自带的索引器,只返回字符串类型。如:名字
var like0 = configuration["Like:0"];//读取数组中第一个元素 如:第一个爱好
var like2 = configuration["Like:2"];//读取数组中第三个元素 如:第三个爱好
var landLit = configuration["Score:LandLit"];//获取字节点的属性值,如:语文成绩

 四、整体对象绑定

新建一个cs类文件,然后复制整个Json文件的内容,依次点击【编辑-->选择性粘贴-->将JSON粘贴为类】菜单

 默认生成的类名为RootObject,然后修改为Student,具体如下所示:

复制代码
namespace TestProjectTools
{
    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类和配置对象进行绑定,如下所示:

//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}");

 

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2019-04-26 百度UEditor的config.json
2019-04-26 [转]解决百度ueditor插入动态地图空白 支持iframe方法
2019-04-26 【转】百度UEditor控件中的map组件不支持https使用的问题解决
2019-04-26 [转]在ASP.NET Core中使用百度在线编辑器UEditor
点击右上角即可分享
微信分享提示