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?
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, eg:
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"]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.