Ph0*_*n1x 8 c# json appsettings asp.net-core-mvc asp.net-core
让我们假设我们有这个部分 appsettings.json
{
"crypto":{
"A": "some value",
"B": "foo foo",
"C": "last part"
},
...
}
Run Code Online (Sandbox Code Playgroud)
"crypto"
某些加密密钥的json序列化在哪里.
稍后在代码中,我需要做这样的事情:
var keyOptions = CryptoProvider.RestoreFromJson(Configuration.GetSection("crypto"))
Run Code Online (Sandbox Code Playgroud)
但是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;
}
}
Run Code Online (Sandbox Code Playgroud)
如果您想获取crypto
该部分的内容,您可以使用
Configuration.GetSection("crypto").AsEnumerable()
(或者对于您的示例Configuration.GetSection("crypto").GetChildren()
可能有用)。
但结果不是原始的 json。你需要转换它。
归档时间: |
|
查看次数: |
487 次 |
最近记录: |