1
votes

On an Asp.Net Core 3.1 application I have the following section on AppSettings:

  "Logins": [
    {
      "Name": "Facebook",
      "Id": "fb_id",
      "Secret": "fb_secret"
    },
    {
      "Name": "Google",
      "Id": "go_id",
      "Secret": "go_secret"
    }
  ]

I am trying to get values, such as Id of Facebook, so I tried:

Configuration.GetValue<String>("Logins:Facebook:Id")

But this won't work ... How can I get the values?

1
Logins and Facebook are sections. Instead of reading strings, why not read the entire Facebook object though? Or read the entire array at once? You could use eg Get or Bind to load strongly-typed objects on startup, register with DI and inject them as needed – Panagiotis Kanavos
You should be able to use Configurrattion.GetSection("Logins").Get<MyLogin[]>() to load the entire array – Panagiotis Kanavos

1 Answers

2
votes

All ASP.NET Core configuration gets converted into key-value pairs. In your example, you end up with key-value pairs that looks like this:

  • Logins:0:Name = Facebook
  • Logins:0:Id = fb_id
  • Logins:0:Secret = fb_secret
  • Logins:1:Name = Google
  • Logins:1:Id = go_id
  • Logins:1:Secret = go_secret

As this shows, there's no key named Logins:Facebook:Id, which is because the JSON structure uses an array. If you want to target the providers by name, update the JSON to use the following structure:

"Logins": {
  "Facebook": {
    "Id": "fb_id",
    "Secret": "fb_secret"
  },
  "Google": {
    "Id": "go_id",
    "Secret": "go_secret"
  }
}

This creates the key-value pairs that you expect, e.g.:

  • Logins:Facebook:Id = fb_id
  • Logins:Facebook:Secret = fb_secret

Also, because these values are already strings, you can, if you prefer, just use something like this to read the value:

Configuration["Logins:Facebook:Id"]