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

弱类型读取:

1. 通过冒号mysql:host

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

强类型读取:

1.GetValue

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

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

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


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

            //强类型读取
            var info = configuration.GetValue("mysql:port",0);
            Console.WriteLine(info);

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

            var rootobject = configuration.Get();
            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]
  
}

 

 

你可能感兴趣的:(.NET,CORE)