How to add values through user secrets to an array of objects in C#
Asked Answered
L

1

12

So I'm having issues trying to get Visual Studio to add user secrets to a property that is an array. I have a feeling this sort of thing can't be done but I really need to have a way of iterating through the each of them for what I'm doing and I'm not allowed to store the clientSecrets in the standard appsettings file for obvious reason.

Is there a way of doing this and if not is there a way I could change this object to make it iterable in C# which also allows me to store the passwords in the user secrets?

The object below shows the current shape of the appsettings which I'm trying to store the values into:

{
  "TestClients": [
    {
      "ClientSecret": ""
    },
    {
      "ClientSecret": ""
    },
    {
      "ClientSecret": ""
    },
    {
      "ClientSecret": ""
    },
    {
      "ClientSecret": ""
    },
    {
      "ClientSecret": ""
    },
    {
      "ClientSecret": ""
    },
    {
      "ClientSecret": ""
    }
  ]
}

I have tried turning it into a object and iterating through the keys but the console app I'm working with doesn't seem to find the section TestClients when the object is shaped like this:

{
   "TestClients": {
       "ClientName": {
           "ClientSecret": ""
       }
   }
}
Lashawn answered 14/2, 2020 at 21:56 Comment(0)
L
20

The Configuration API reads hierarchical configuration data by flattening the hierarchical data with the use of a delimiter in the configuration keys. And usersecrets uses the same flatten structure with a delimeters in the keys.

So the solution is to put in your secrets.json something like this

{
  "TestClients:0:ClientSecret": "Some secret",
  "TestClients:1:ClientSecret": "Other secret",
  "TestClients:2:ClientSecret": "Next secret"
}

You can find more details in the documentation: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1#hierarchical-configuration-data https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1#boa

Lettering answered 29/4, 2020 at 8:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.