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

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

程序员文章站 2022-03-17 17:54:29
...
前言:在与传统的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": "*"
}

.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配置文件

控制器中使用:

{
  "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号"
        }
      ]
    }
  }
  //==============================
}

.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配置文件

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

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

相关标签: .net 读取json