.Net Core读取Json配置文件的实现示例

 更新时间:2019年11月25日 11:15:05   作者:江北、  
这篇文章主要介绍了.Net Core读取Json配置文件的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

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

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

 }
}

当然也可以读取数组形式的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<T>来读取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; }
 }
}

在Startup中添加如下代码

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

控制器中使用:

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

namespace Read.json.Controllers
{
 [Route("api/[controller]/[action]")]
 [ApiController]
 public class ReadController : Controller
 {
  private IConfiguration _configuration;

  readonly Information _Information;

  readonly IOptions<Information> _options;
  public ReadController(IConfiguration configuration,
        Information Information,
        IOptions<Information> options)
  {
   _configuration = configuration;
   _Information = Information;
   _options = options;
  }

  [HttpGet]
  public async Task<IActionResult> ReadInformation()
  {
   string Address = _options.Value.school.Region.Province + "-" +
        _options.Value.school.Region.City + "-" +
        _options.Value.school.Region.Area + "-" +
        _options.Value.school.Detailed_address[0].Address + "-" +
        _options.Value.school.Introduce.Name + "-" +
        _options.Value.school.Introduce.Class + "-" +
        _options.Value.school.Introduce.Number;
   return Json(Address);
  }

  [HttpPost]
  public async Task<string> ReadJson()
  {
   string conn = _configuration["Connection:dbContent"];
   string commodity = _configuration["Content:0:Trade_name:test1"];
   return "";
  }

 }
}

第三种:这种应该比较常见,任意读取自定义的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
   });
  }

Demo地址:https://github.com/Davenever/Read_Json.git

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • ASP.NET MVC5验证系列之客户端验证

    ASP.NET MVC5验证系列之客户端验证

    这篇文章主要为大家详细介绍了ASP.NET MVC5验证系列之客户端验证,感兴趣的小伙伴们可以参考一下
    2016-07-07
  • 让VS2008对JQuery语法的智能感知更完美一点

    让VS2008对JQuery语法的智能感知更完美一点

    上周Rich Strahl的POST中提到一个新发布的VS2008 hotfix修复了VS2008对Javascript智能感知的一些BUG,fixed之后可以让VS2008对JQuery提供智能感知,让我等JQuery fans欣喜了一阵子。可仔细一看,还需要另外给JQuery添加上XML comments才行 :( 丧气了...  
    2008-03-03
  • ASP.NET对txt文件相关操作(读取、写入、保存)

    ASP.NET对txt文件相关操作(读取、写入、保存)

    这篇文章主要介绍了ASP.NETtxt文件相关操作,包括读取、写入、保存,需要的朋友可以参考下
    2015-09-09
  • .Net ORM 访问 Firebird 数据库的方法

    .Net ORM 访问 Firebird 数据库的方法

    这篇文章简单介绍了在 .net6.0 环境中使用 FreeSql 对 Firebird 数据库的访问,目前 FreeSql 还支持.net framework 4.0 和 xamarin 平台上使用,对.Net ORM 访问 Firebird 数据库相关知识感兴趣的朋友一起看看吧
    2022-07-07
  • ASP.NET下上传图片到数据库,并且读出图片的代码(详细版)

    ASP.NET下上传图片到数据库,并且读出图片的代码(详细版)

    上传图片到数据库,从数据库的创建到数据库中图片的现实都给出了具体的代码,因为asp.net版本的问题,大家可能需要稍微修改下。
    2010-07-07
  • 基于ABP框架实现数据字典开发

    基于ABP框架实现数据字典开发

    本文详细讲解了基于ABP框架实现数据字典开发,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-12-12
  • ADO.NET实用经验汇总

    ADO.NET实用经验汇总

    这篇文章主要介绍了ADO.NET实用经验汇总,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-12-12
  • 如何取消.net后台线程的执行

    如何取消.net后台线程的执行

    在使用多线程模型进行编程时,经常遇到的问题之一是,当我们关闭前台的UI线程时,后台的辅助线程仍然处于活动状态,从而导致整个应用程序无法正常退出
    2012-11-11
  • MVC使用T4模板生成其他类的具体实现学习笔记2

    MVC使用T4模板生成其他类的具体实现学习笔记2

    这篇文章主要为大家详细介绍了MVC使用T4模板生成其他类的具体实现,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-09-09
  • VS+opencv实现鼠标移动图片

    VS+opencv实现鼠标移动图片

    这篇文章主要为大家详细介绍了VS+opencv实现鼠标移动图片,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-01-01

最新评论