欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-04-10 08:55:03
前言:在与传统的asp.net mvc项目相比,.net core项目在项目目录的文件结构上和功能上与前者都有很大的区别。例如:在.net core中使用startup.cs取代glo...

前言:在与传统的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": "*"
}

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

在控制器中注入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 "";
  }

 }
}

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

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

.Net Core读取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": "*",

 //==============================
 "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

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

控制器中使用:

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

 }
}

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

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

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

首先建立一个json文件

{
 "system_version": {
 "edition": ".net core 3.0",
 "project_name": "read.json"
 }
}

.Net Core读取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();

  }

 }
}

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

在控制器中调用:

[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
   });
  }

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

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

demo地址:https://github.com/davenever/read_json.git

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