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

标签 c# asp.net asp.net-core

我在 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/

相关文章:

c# - 在 C# 中 try catch 的不同方法

c# - 数据库到 DropDownList 和 AutoPostBack 到标签

c# - 自托管 Web Api 服务到 Windows 窗体

asp.net-core - ASP.NET Core Web 应用程序中的语言未更改

c# - 我的网络应用程序应该有多大的弹性?

c# - 如何在 Entity Framework 6 中重命名 DBContext

c# - 是否有适合初学者的元组的实际示例?

asp.net - Windows Azure 上的简单文件上传

jenkins - 使用 dotnet Restore 设置 npm 私有(private)注册表

c# - .net 核心中的 httprequest.UserHostName