netcore-通过弱类型和强类型读取json配置文件

弱类型读取:

1. 通过冒号mysql:host

2.GetSection("mysql")["host"]

强类型读取:

1.GetValue<T>

2.配置映射成实体类Bind,Get<T>

using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {

            //SetBasePath必须要引入Microsoft.Extensions.Configuration.json包才会有
            IConfiguration configuration = new ConfigurationBuilder().SetBasePath(Environment.CurrentDirectory)
                .AddJsonFile("appsettings.json").Build();

            //弱类型读取
            //var info = configuration["shopidlist:2"];
            //var info = configuration.GetSection("shopidlist").GetSection("2").Value;
            //Console.WriteLine(info);

            //强类型读取
            //GetValue()必须是要引入Microsoft.Extensions.Configuration.Binder包才会有
            var info = configuration.GetValue<int>("mysql:port",0);
            Console.WriteLine(info);

            //Rootobject rootobject = new Rootobject();
            //configuration.Bind(rootobject);

            var rootobject = configuration.Get<Rootobject>();
            Console.ReadLine();
        }
    }

    public class Rootobject
    {
        public Mysql mysql { get; set; }
        public int[] shopidlist { get; set; }
    }

    public class Mysql
    {
        public string host { get; set; }
        public string port { get; set; }
    }


}
{
  "mysql": {
    "host": "192.168.23.1",
    "port": "3306"
  },
  "shopidlist": [10,20,30,40]
  
}

 

 

相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页