C# 如何为appsettings.json复杂数组使用选项模式
我在.NET核心控制台应用程序中有以下appsettings.json。本页所示示例不包括复杂类型的应用程序设置 如何在以下应用程序设置中遍历每种报告类型的列C# 如何为appsettings.json复杂数组使用选项模式,c#,asp.net-core,configuration,settings,asp.net-core-3.1,C#,Asp.net Core,Configuration,Settings,Asp.net Core 3.1,我在.NET核心控制台应用程序中有以下appsettings.json。本页所示示例不包括复杂类型的应用程序设置 如何在以下应用程序设置中遍历每种报告类型的列 { "Reports": [ { "name": "Roles", "fileName": "roles.csv", "columns": [ {
{
"Reports": [
{
"name": "Roles",
"fileName": "roles.csv",
"columns": [
{
"name": "ROLE_ID",
"default": ""
},
{
"name": "NAME",
"default": ""
},
{
"name": "AVAILABILITY_IND",
"default": "YES"
}
]
},
{
"name": "Accounts",
"fileName": "accounts.csv",
"columns": [
{
"name": "ROLE",
"default": "NONE"
},
{
"name": "USER_ID",
"default": ""
},
{
"name": "LASTNAME",
"default": ""
},
{
"name": "FIRSTNAME",
"default": ""
}
]
}
]
}
您可以读取嵌套数组,如下所示:
public class HomeController : Controller
{
private readonly IConfiguration _configuration;
public HomeController(IConfiguration configuration)
{
_configuration = configuration;
}
public IActionResult Index()
{
//read the first report's columns array's first item's name------"ROLE_ID"
var data = _configuration.GetSection("Reports:0:columns:0:name");
return View();
}
有关如何获取所有键和值的:
var model = _configuration.GetSection("Reports").AsEnumerable();
foreach (var kv in model)
{
Console.WriteLine("{0}: {1}", kv.Key, kv.Value);
}
您还可以将json反序列化到模型并从模型中获取项:
型号:
public class Rootobject
{
public Report[] Reports { get; set; }
}
public class Report
{
public string name { get; set; }
public string fileName { get; set; }
public Column[] columns { get; set; }
}
public class Column
{
public string name { get; set; }
public string _default { get; set; }
}
控制器:
var json = System.IO.File.ReadAllText("yourJsonfile.json");
var DeserializeModel = JsonSerializer.Deserialize<Rootobject>(json);
那么您想绑定一个类的数组,其中包含另一个类类型的数组?仅仅因为示例使用基本类型来简化,并不意味着您不能组合来自不同示例的概念。这不是面向对象的。此外,在控制器内部,从硬盘读取设置文件,然后反序列化这些文件是不正常的。正确的模式是使用依赖项注入将设置传递到控制器。因为可以在设置文件的顶部覆盖其他设置层,如命令行参数和环境变量。。。此外,您还可以拥有多个设置文件,这也是.NETCore中的一种常见模式
public class Startup
{
public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
configuration = new ConfigurationBuilder().SetBasePath(env.ContentRootPath)
.AddJsonFile("test.json")
.Build();
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddSingleton<IConfiguration>(Configuration);
}
}