How .Net Core reads Json configuration files

angryTom
Release: 2019-11-27 14:56:40
forward
4155 people have browsed it

Preface: Compared with the traditional asp.net MVC project, the .net core project is very different from the former in the file structure and function of the project directory. For example: Use Startup.cs in .net core to replace the Global.asax file to load the application configuration and various startup items. appsettings.json replaces the web.config file and is used to store configuration parameters required by the application, etc. . .

How .Net Core reads Json configuration files

OK! Getting to the point, let’s talk about how to read the parameters in the Json configuration file.

First method: use IConfiguration interface

We first configure the database connection string in appsettings.json, and then read it

{
  "Connection": {
    "dbContent": "Data Source=.;Initial Catalog=test;User ID=sa;Password=123456"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}
Copy after login

Inject the IConfiguration interface into the controller

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

    }
}
Copy after login

Of course, you can also read json in the form of an array. The same is done first in appsettings.json Write the configuration parameters as follows:

{
  "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": "*"
}
Copy after login

For example, we want to read test1

string commodity_test1 = _configuration["Content:0:Trade_name:test1"];
Copy after login

Second: use IOptions to read the json configuration file

First import the NuGet package into the project: Microsoft.Extensions.Options.ConfigurationExtensions

First add the node in appsettings.json as follows

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

Then create a class that is "same" as this node

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; }
    }
}
Copy after login

Add the following code in Startup

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

Use in the controller:

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

The third type: This should be more common, read any custom json file

First create a json file

{
  "system_version": {
    "Edition": ".Net Core 3.0",
    "Project_Name": "Read.json"
  }
}
Copy after login

Create a class and encapsulate a method

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();

        }

    }
}
Copy after login

Call in the controller:

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

This article comes from C#.Net Tutorial column, welcome to learn!

The above is the detailed content of How .Net Core reads Json configuration files. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!