问题
I have the following appSettings.json file:
"SundrySettings": {
"CookieName": "Cookie",
"AccessGroup": "Software Development",
"Terminals" : {
"Raucherplatz" : "tablet1.local",
"Service" : "tablet2.local",
"Technik" : "tablet3.local",
"Technik" : "tablet4.local",
"Container" : "tablet5.local"
}
}
}
That I would like to load into the following structure:
public class Terminal
{
public string Name;
public string Description;
}
public class SundryOptions
{
public string CookieName { get; set; } = "dummy";
public string HRAccessGroup { get; set; } = "dummy";
public List<Terminal> Terminals;
}
that I would try to load using the following commands:
ServiceProvider sp = services.BuildServiceProvider();
SundryOptions sundryOptions = sp.GetService<IOptions<SundryOptions>>().Value;
The problem I have is that using Property Initialisers never sets the Terminals List correctly. I do need a list (and not a Dictionary) as the enties could be double i.e. Technik in my example.
I am assuming that I have some error in the Class -> I would be happy for any pointers.
回答1:
Implement processing of configuration as following somewhere approporiate like this:
var cookieName =
Configuration.GetSection("SundrySettings:CookieName").Value;
var accessGroup = Configuration.GetSection("SundrySettings:AccessGroup").Value;
var terminals = new List<Terminal>()
var terminalSections = this.Configuration.GetSection("Terminals").GetChildren();
foreach (var item in terminalSections)
{
terminals.Add(new Terminal
{
// perform type mapping here
});
}
SundryOptions sundryOption = new SundryOptions()
{
CookieName = cookieName,
HRAccessGroup = accessGroup,
Terminals = terminalList
};
Of course there could be shorter version, but you can start from here.
回答2:
Do as follows:
var cookieName = Configuration.GetSection("SundrySettings:CookieName").Value;
var accessGroup = Configuration.GetSection("SundrySettings:AccessGroup").Value;
var terminals = Configuration.GetSection("SundrySettings:Terminals").GetChildren();
List<Terminal> terminalList = new List<Terminal>();
foreach (var keyValuePair in terminals)
{
Terminal termial = new Terminal()
{
Name = keyValuePair.Key,
Description = keyValuePair.Value
};
terminalList.Add(termial);
}
SundryOptions sundryOption = new SundryOptions()
{
CookieName = cookieName,
HRAccessGroup = accessGroup,
Terminals = terminalList
};
I have checked with the exact configuration you provided and it works perfectly.
回答3:
If Terminals is a list, in your appSettings, it should be an array, not an object.
"Terminals" : [
"Raucherplatz" : "tablet1.local",
"Service" : "tablet2.local",
"Technik" : "tablet3.local",
"Technik" : "tablet4.local",
"Container" : "tablet5.local"
]
来源:https://stackoverflow.com/questions/54692345/how-to-read-appsettings-json-with-array-of-values