I am building a C# .NET 5.0 application to talk to an external API for which we have multiple accounts that we can post data to. I am trying to store these details in appsettings.json file and use the options pattern to retrieve the settings.
I have the following structure in my app settings.json
"SomeApi": {
"Url": "https://api.someapi.net/v3/",
"Secret": "mysecretvlaue",
"ClientId": "myclientid",
"Accounts": [
{
"Name": "Bob",
"Username": "HisUsername",
"Password": "HisPassword",
"PostingLocation": "HisLocation"
},
{
"Name": "Fred",
"Username": "HisUsername",
"Password": "HisPassword",
"PostingLocation": "HisLocation"
}
]
},
I have a class set up like this:
public class SomeApiOptions
{
public const string SomeApi = "SomeApi";
public string Url { get; set; }
public string Secret { get; set; }
public string ClientId { get; set; }
public List<Account> Accounts { get; set; }
}
public class Account
{
string Name { get; set; }
string Username { get; set; }
string Password { get; set; }
string PostingLocation { get; set; }
}
My startup.cs has this:
services.Configure<SomeApiOptions>(Configuration.GetSection(SomeApiOptions.SomeApi));
Finally, I inject IOptions to the class where I need to use the settings like so:
Public MyClass (IOptionsSnapshot<SomeApiOptions> options)
The issue I am having is the Accounts never get populated with their respective values.
Url, Secret etc. are populated and the number of elements items in the Accounts list is correct, but all of the properties have null values.
I have looked at similar questions and tried restructuring my JSON a few ways but still end up with null values.
Any help greatly appreciated.
Accountclass are public so you need to change that. Second, theLocationproperty doesn't match the JSON which isPostingLocation.PostingLocationwhile its name in object isLocationtry to make them same or... add data Annotation to your object