Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IConfiguration Bind doesn't work with arrays

I have to set a string array in the configuration when starting an ASP.NET Core web application. I get the string array from Azure Key Vault, and it works fine. It's only included in the code below for context.

Here is the relevant content of appsettings.json:

{
   "SecretName": "mysecrect",   // key for secret in Azure Keyvault
   "secret": "hush~hush~1234",  // to be replaced
   "AdminKey": "admin-list",    // key for admin list in Azure Key Vault
   "Admins": ["a", "b"]         // to be replaced
}

Code in the Program.cs:

// For reference
var kvUri = $"https://abcd1234.vault.azure.net";
var client = new SecretClient(new Uri(kvUri), new DefaultAzureCredential());
var secretName = builder.Configuration["SecretName"];
var secret = client.GetSecret(secretName);                // returns "hemlig~nemlig1234"
builder.Configuration.Bind("Secret", secret.Value.Value); // this Bind works fine. the old value is replaced
   
// Here comes the problem
var Admkey = builder.Configuration["AdminKey"]; // returns "admin-list"                
var Adm = client.GetSecret(AdmKey);             // returns "alice,bob"
var s = konAdm.Value.Value.Split(',');
var json = JsonConvert.SerializeObject(s);      // creates ["alice","bob"]
builder.Configuration.Bind("Admins", json);     // ["a", "b"] are NOT replaced with ["alice","bob"]

How can I use builder.Configuration.Bind to work with an array?

Inserting the string array: s doesn't work either.

like image 566
Anders Finn Jørgensen Avatar asked Dec 13 '25 02:12

Anders Finn Jørgensen


1 Answers

From Memory configuration provider, you should use AddInMemoryCollection to update the configuration key-value pairs.

As you are updating the array, you have to specify the key-value pair as:

[Admins:0]: alice
[Admins:1]: bob
using System.Linq;

// Assume s returns ["alice","bob"]

Dictionary<string, string> adminKeyValuePairs = s
    .Select((x, i) => ($"Admins:{i}", x))
    .ToDictionary(x => x.Item1, x => x.Item2);
builder.Configuration.AddInMemoryCollection(adminKeyValuePairs);

// To check whether the Admins updated in the configuration provider
var admins = builder.Configuration.GetSection("Admins").Get<List<string>>();
like image 115
Yong Shun Avatar answered Dec 15 '25 15:12

Yong Shun