假设我们在 appsettings.json
{
"crypto":{
"A": "some value",
"B": "foo foo",
"C": "last part"
},
...
}
"crypto"
是一些加密 key 的 json 序列化。
在代码的后面,我需要做这样的事情:
var keyOptions = CryptoProvider.RestoreFromJson(Configuration.GetSection("crypto"))
但是 Configuration.GetSection
返回 ConfigurationSection
实例。有没有办法以某种方式获取其背后的原始 json 数据?
我假设 ConfigurationSection.Value
应该可以解决问题,但由于某些原因它总是 null
。
最佳答案
这是一个实现示例。
private static JToken BuildJson(IConfiguration configuration)
{
if (configuration is IConfigurationSection configurationSection)
{
if (configurationSection.Value != null)
{
return JValue.CreateString(configurationSection.Value);
}
}
var children = configuration.GetChildren().ToList();
if (!children.Any())
{
return JValue.CreateNull();
}
if (children[0].Key == "0")
{
var result = new JArray();
foreach (var child in children)
{
result.Add(BuildJson(child));
}
return result;
}
else
{
var result = new JObject();
foreach (var child in children)
{
result.Add(new JProperty(child.Key, BuildJson(child)));
}
return result;
}
}
关于c# - 获取 ConfigurationSection 的初始 JSON 表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37525604/