温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

.NET Core如何读取json配置文件

发布时间:2021-06-28 14:53:26 来源:亿速云 阅读:203 作者:小新 栏目:开发技术

这篇文章主要介绍了.NET Core如何读取json配置文件,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

背景

  目前发现网上的 .NET Core 读取 json 格式的配置文件有点麻烦,自己想搞个简单点的。

  .NET Core 目前的主流形式是采用 json 格式来存储配置文件信息,跟之前的诸如 app.config 和 web.config 等 xml 形式的配置文件有所区别。 

.NET Core如何读取json配置文件

json 文件 demo

appsettings.json:

{
 "name": "wen",
 "age": 26,
 "family": {
 "mother": {
  "name": "娘",
  "age": 55
 },
 "father": {
  "name": "爹",
  "age": 56
 }
 }
}

Nuget 类库引用

  需要 Nuget 两个类库:

  ①Microsoft.Extensions.Configuration

  ②Microsoft.Extensions.Configuration.Json

核心代码:

Program.cs:

using System;
using System.IO;
using Microsoft.Extensions.Configuration;

namespace Demo
{
 class Program
 {
  static void Main(string[] args)
  {
   //添加 json 文件路径
   var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
   //创建配置根对象
   var configurationRoot = builder.Build();

   //取配置根下的 name 部分
   var nameSection = configurationRoot.GetSection("name");
   //取配置根下的 family 部分
   var familySection = configurationRoot.GetSection("family");
   //取 family 部分下的 mother 部分下的 name 部分
   var motherNameSection = familySection.GetSection("mother").GetSection("name");
   //取 family 部分下的 father 部分下的 age 部分
   var fatherAgeSection = familySection.GetSection("father").GetSection("age");

   //Value 为文本值
   Console.WriteLine($"name: {nameSection.Value}");
   Console.WriteLine($"motherName: {motherNameSection.Value}");
   Console.WriteLine($"fatherAge: {fatherAgeSection.Value}");
   Console.Read();
  }
 }
}

测试结果:

.NET Core如何读取json配置文件

直观的关系对比图,可以看到核心就是 GetSection() 方法,每继续往下一个层次获取就再次调用 GetSection() 方法:

.NET Core如何读取json配置文件

备注

别忘了设置 json 文件的属性哦:

.NET Core如何读取json配置文件

感谢你能够认真阅读完这篇文章,希望小编分享的“.NET Core如何读取json配置文件”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI