【问题标题】:How to override an ASP.NET Core configuration array setting reducing length of the array如何覆盖 ASP.NET Core 配置数组设置以减少数组的长度
【发布时间】:2019-01-07 22:24:07
【问题描述】:

我有一个带有 appsettings.json 配置文件的 ASP.NET Core 应用程序。文件中的一项设置由对象数组表示,如下所示:

{
  "Globalization": {
    "Languages": [
      {
        "DisplayName": "Ru",
        "Code": "ru"
      },
      {
        "DisplayName": "En",
        "Code": "en"
      }
    ]
  }
}

在我们的 CI 系统中,我们使用环境变量来覆盖文件中的配置设置。事实证明,我只能覆盖现有项目或向数组中添加新项目,但不能使用索引表示法减少项目数量("Globalization__Languages__0__DisplayName" 等)。

appsettings.{Environment}.json 也是如此,即使我只有一项,我仍然有两种语言选择。

当然,我可以将基本配置设为空或发明一些其他解决方法,但我是否遗漏了什么?有什么方法可以巧妙地覆盖设置以减少项目数量(最好借助环境变量)?

【问题讨论】:

    标签: asp.net-core configuration


    【解决方案1】:

    所以默认配置是由虚拟主机构建的。它将包括 appsettings.json(可选)、appsettings.{environment}.json(可选)和环境变量。遗憾的是,如果您在其中一个中设置不同的值,您仍然会收到所有值。

    您可以做的是为特定环境手动构建配置,并且该环境文件将仅包含您未作为环境变量提供的信息。

    为 IHostingEnvironment 创建一个扩展方法

    public static class HostingEnvironmentExtensions
    {
       public static bool IsCi(this IHostingEnvironment environment) 
       {
           return environment.EnvironmentName == "CI" // or give it what ever name you want.
       }
    }
    

    在构造函数中的启动类中执行以下操作

    private readonly IConfiguration configuration;
    public Startup(IConfiguration configuration, IHostingEnvironment environment)
    {
        if (!environment.IsCi())
        {
            this.configuration = configuration;
            return;
        }
    
        this.configuration = new ConfigurationBuilder()
            .AddJsonFile(Path.Combine(AppContext.BaseDirectory, $"appsettings.{environment.EnvironmentName}.json"), false)
            .AddEnvironmentVariables()
            .Build();
    }
    

    现在您只会收到想要的配置,但需要一些开销。

    【讨论】:

      【解决方案2】:

      Microsoft community 做出了一个非常糟糕的决定,让数组以这种方式工作(恕我直言)。

      作为解决方案,我们制定如下:

      {
        "Globalization": {
          "Languages": "ru|Ru,en|En"
        }
      }
      

      然后:

      var langs = Configuration.GetSection("Globalization:Languages")
          .Split(',')
          .Select(x => x.Split('|'))
          .Select(x => new { Code = x[0], DisplayName = x[1] })
          .ToArray();
      

      我的提议是here

      【讨论】:

        猜你喜欢
        • 2016-10-06
        • 2015-01-28
        • 1970-01-01
        • 2016-03-13
        • 1970-01-01
        • 1970-01-01
        • 2018-07-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多