简体   繁体   English

是否可以将强类型数组绑定为ASP.NET Core中的配置模型?

[英]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.

相关问题 无法使用 Asp.Net Core 3 中的命名选项读取/绑定具有强类型 class 的配置设置 - Unable to read/bind configuration settings with strongly-typed class using Named Options in Asp.Net Core 3 强类型的ASP.Net Core实时更新配置 - ASP.Net Core live update configuration on strongly typed 如何在ASP.NET Core中设置强类型配置? - How to set up strongly typed configuration in ASP.NET Core? 在 ASP.net 核心应用程序的强类型配置类中使用 System.Uri - Use System.Uri in strongly typed configuration class for ASP.net core app ASP.NET 5:如何在更改时重新加载强类型配置 - ASP.NET 5: How to reload strongly typed configuration on change .net 核心控制台应用程序强类型配置 - .net core console app strongly typed configuration .net core控制台应用程序强类型配置 - .net core Console application strongly typed Configuration 是否可以直接在ASP.NET 5(vNext)的类库中访问强类型的配置设置? - Accessing strongly typed configuration settings directly into class library in ASP.NET 5 (vNext)? 如何在asp.net core中以强类型方式获取资源字符串? - How to get resource strings in strongly typed way in asp.net core? ASP.Net Core MVC 如何针对强类型模型发布未知数量的字段 - ASP.Net Core MVC how to post unknown number of fields against strongly-typed model
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM