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.
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>>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With