假设存在这样的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