问题
When we have configuration like this
// appsettings.json
{
"SomeServiceConfiguration": {
"Server": "127.0.0.1",
"Port": "25"
}
}
it is possible to use binding to access data:
IConfiguration configuration = ...;
var section = configuration.GetSection("SomeServiceConfiguration");
var val = section.Value; // this is null
var t = new SomeServiceConfiguration();
section.Bind(t);
But is it possible to get value (section content) "just as string" (by the fact as json) {"Server": "127.0.0.1", "Port": "25"}
?
回答1:
According to ConfigurationSection Class this is not directly possible.
However, you could serialize to XML using the ConfigurationElement.SerializeElement(XmlWriter, Boolean) Method, which is possible by default. You would have to convert to JSON afterwards, so this seems overkill.
I would recommend building a new JSON Object
and accessing the section values directly.
来源:https://stackoverflow.com/questions/52012599/microsoft-configuration-extensions-how-to-get-section-complex-value-as-json-s