[英]Is it possible to bind strongly typed arrays as configuration models in ASP.NET Core?
I have defined the following in my appsettings.json
... 我在appsettings.json
定义了以下appsettings.json
......
{
"Environments": [
{
"Name": "One",
"CloudServices": [
"name1",
"name2"
]
},
{
"Name": "Two",
"CloudServices": [
"name3",
"name4"
]
}
]
}
...and the following strongly typed models: ......以及以下强类型模型:
public class EnvironmentModel
{
public string Name { get; set; }
public string[] CloudServices { get; set; }
}
public class EnvironmentsConfig
{
public EnvironmentModel[] Environments { get; set; }
}
I was hoping I could bind this in my Startup
like this: 我希望我可以像我这样在我的Startup
绑定它:
services.Configure<EnvironmentsConfig>(Configuration.GetSection("Environments"));
However, when injected into my controller as IOptions<EnvironmentsConfig>
the value is null. 但是,当作为IOptions<EnvironmentsConfig>
注入我的控制器时,该值为null。 Is it possible to bind strongly typed arrays like this? 是否可以像这样绑定强类型数组? If not, what is the recommended approach? 如果没有,推荐的方法是什么? The number of environments may differ between deployments hence my need for an array. 部署之间的环境数量可能不同,因此我需要一个阵列。
The Environments
section of your configuration contains an array of EnvironmentModel
, not an EnvironmentsConfig
. 配置的“ Environments
部分包含EnvironmentModel
数组,而不是EnvironmentsConfig
。 To fix it you just need to use the root of your config instead of a section. 要修复它,您只需使用配置的根而不是部分。 For example: 例如:
services.Configure<EnvironmentsConfig>(Configuration);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.