5

I have an ASP.NET Core app with appsettings.json config file. One of the settings in the file is represented by the array of objects, like this:

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

In our CI system we use environment variables to override the configuration settings from file. It turns out that I can only override existing items or add new items to the array, but I can’t reduce the number of items using index notation ("Globalization__Languages__0__DisplayName" etc.).

And it’s the same with appsettings.{Environment}.json, I still have two language options even if I have just one item in it.

Of course I can make the base config empty or invent some other workaround, but am I missing something? Is there any way to neatly override the settings reducing the number of items (preferably with the help of environment variables)?

1 Answer 1

4

Microsoft community made a very bad design decision to make arrays work in that way (IMHO).

As a solution we worked it out as the follows:

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

and then:

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

My proposal is here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.