.net core读取appsettings.json的配置

假设存在这样的json配置文件

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*","Level": {
    "A": "Good",
    "Other": [
      "B","C","D"
    ]
  }
}

想分别读取配置

在控制器中:

        private readonly IConfiguration _config;

        public HomeController(IConfiguration config)
        {
            _config = config;
        }

 

            #region 读取配置
            Console.WriteLine(_config["AllowedHosts"]);  //一级
            Console.WriteLine(_config["Logging:LogLevel:Default"]);  //多级单个
            Console.WriteLine(_config["Level:Other:0"]);  //多级多个
            var levels = _config.GetSection("Level").GetSection("Other").GetChildren().Select(v => v.Value).ToArray(); //全部
            foreach (var item in levels)
            {
                Console.WriteLine(item);
            }
            #endregion

 

上一篇:ASP.NET Core 根据环境变量支持多个 appsettings.json配置文件


下一篇:asp.net core 读取 appsettings.json 节点值