gpt4 book ai didi

c# - 是否可以将强类型数组绑定(bind)为 ASP.NET Core 中的配置模型?

转载 作者:太空宇宙 更新时间:2023-11-03 22:48:42 24 4
gpt4 key购买 nike

我在 appsettings.json 中定义了以下内容...

{
"Environments": [
{
"Name": "One",
"CloudServices": [
"name1",
"name2"
]
},
{
"Name": "Two",
"CloudServices": [
"name3",
"name4"
]
}
]
}

...以及以下强类型模型:

public class EnvironmentModel
{
public string Name { get; set; }
public string[] CloudServices { get; set; }
}

public class EnvironmentsConfig
{
public EnvironmentModel[] Environments { get; set; }
}

我希望我可以在我的 Startup 中绑定(bind)它像这样:

services.Configure<EnvironmentsConfig>(Configuration.GetSection("Environments"));

但是,当作为 IOptions<EnvironmentsConfig> 注入(inject)我的 Controller 时该值为空。是否可以像这样绑定(bind)强类型数组?如果不是,推荐的方法是什么?部署之间的环境数量可能不同,因此我需要一个阵列。

最佳答案

配置的 Environments 部分包含一个 EnvironmentModel 数组,而不是 EnvironmentsConfig。要修复它,您只需要使用配置的根而不是部分。例如:

services.Configure<EnvironmentsConfig>(Configuration);

关于c# - 是否可以将强类型数组绑定(bind)为 ASP.NET Core 中的配置模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48649017/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com