登录  /  注册

.Net Core如何读取Json配置文件

angryTom
发布: 2019-11-27 14:55:50
转载
4002人浏览过

前言:在与传统的asp.net mvc项目相比,.net core项目在项目目录的文件结构上和功能上与前者都有很大的区别。例如:在.net core中使用startup.cs取代global.asax文件用于加载应用程序的配置和各种启动项。appsettings.json取代web.config文件用于存储应用程序所需的配置参数等等。。。

.Net Core如何读取Json配置文件

OK!步入正题,下面来说一下如何读取Json配置文件中的参数。

第一种:使用IConfiguration接口

我们先在appsettings.json中配置好数据库连接字符串,然后读取它

{
  "Connection": {
    "dbContent": "Data Source=.;Initial Catalog=test;User ID=sa;Password=123456"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}
登录后复制

 在控制器中注入IConfiguration接口

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace Read.json.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class ReadController : Controller
    {
        private IConfiguration _configuration;
        public ReadController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        [HttpPost]
        public async Task<string> ReadJson()
        {
            //读参
            string conn = _configuration["Connection:dbContent"];
            return "";
        }

    }
}</string>
登录后复制

 当然也可以读取数组形式的json,一样的先在appsettings.json中写好配置参数,如下:

{
  "Connection": {
    "dbContent": "Data Source=.;Initial Catalog=test;User ID=sa;Password=123456"
  },

  //------------------------
  "Content": [
    {
      "Trade_name": {
        "test1": "小熊饼干",
        "test2": "旺仔QQ糖",
        "test3": "娃哈哈牛奶"
      }
    }
  ],
  //------------------------

  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}
登录后复制

比如我们想读取test1

string commodity_test1 = _configuration["Content:0:Trade_name:test1"];
登录后复制

 第二种:使用IOptions来读取json配置文件

先把NuGet包导进项目:Microsoft.Extensions.Options.ConfigurationExtensions

 首先在appsettings.json中添加节点如下

{
  "Connection": {
    "dbContent": "Data Source=.;Initial Catalog=test;User ID=sa;Password=123456"
  },

  //------------------------
  "Content": [
    {
      "Trade_name": {
        "test1": "小熊饼干",
        "test2": "旺仔QQ糖",
        "test3": "娃哈哈牛奶"
      }
    }
  ],
  //------------------------

  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",

  //==============================
  "Information": {
    "school": {
      "Introduce": {
        "Name": "实验小学",
        "Class": "中班",
        "Number": "15人"
      },
      "Region": {
        "Province": "湖北",
        "City": "武汉",
        "Area": "洪山区"
      },
      "Detailed_address": [
        {
          "Address": "佳园路207号"
        }
      ]
    }
  }
  //==============================
}
登录后复制
登录后复制

 然和再建立一个与这个节点"相同"的类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Read.json
{
    public class Information
    {
        public School school { get; set; }
    }
    public class School
    {
        public Introduce Introduce { get; set; }

        public Region Region { get; set; }

        public List<detailed_address> data { get; set; }

    }
    public class Introduce
    {
        public string Name { get; set; }
        public string Class { get; set; }
        public string Number { get; set; }
    }

    public class Region
    {
        public string Province { get; set; }
        public string City { get; set; }
        public string Area { get; set; }
    }
    public class Detailed_address
    {
        public string Address { get; set; }
    }
}</detailed_address>
登录后复制

 在Startup中添加如下代码

            #region 服务注册,在控制器中通过注入的形式使用
            services.AddOptions();
            services.Configure<information>(Configuration.GetSection("Information"));            #endregion</information>
登录后复制

 控制器中使用:

{
  "Connection": {
    "dbContent": "Data Source=.;Initial Catalog=test;User ID=sa;Password=123456"
  },

  //------------------------
  "Content": [
    {
      "Trade_name": {
        "test1": "小熊饼干",
        "test2": "旺仔QQ糖",
        "test3": "娃哈哈牛奶"
      }
    }
  ],
  //------------------------

  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",

  //==============================
  "Information": {
    "school": {
      "Introduce": {
        "Name": "实验小学",
        "Class": "中班",
        "Number": "15人"
      },
      "Region": {
        "Province": "湖北",
        "City": "武汉",
        "Area": "洪山区"
      },
      "Detailed_address": [
        {
          "Address": "佳园路207号"
        }
      ]
    }
  }
  //==============================
}
登录后复制
登录后复制

 

第三种:这种应该比较常见,任意读取自定义的json文件

首先建立一个json文件

{
  "system_version": {
    "Edition": ".Net Core 3.0",
    "Project_Name": "Read.json"
  }
}
登录后复制

再建一个类,封装一个方法

using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Read.json
{
    public class Json_File
    {
        public IConfigurationRoot Read_Json_File()
        {
            //这句代码会读取read_json.json中的内容
            return new ConfigurationBuilder().AddJsonFile("read_json.json")
                                             .Build();

        }

    }
}
登录后复制

在控制器中调用:

[HttpGet]
        public async Task<iactionresult> ReadSystemVersion()
        {
            var configuration = _json_File.Read_Json_File();
            string system = "使用的是" + configuration["system_version:Edition"] + "的版本" + "," +
                            "项目名称是" + configuration["system_version:Project_Name"];
            return Json(new
            {
                data = system
            });
        }</iactionresult>
登录后复制

 

 

 本文来自 C#.Net教程 栏目,欢迎学习!  

以上就是.Net Core如何读取Json配置文件的详细内容,更多请关注php中文网其它相关文章!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:博客园网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
最新问题
关于CSS思维导图的课件在哪? 课件
凡人来自于2024-04-16 10:10:18
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号