Let's assume we have this section in appsettings.json
{
"crypto":{
"A": "some value",
"B": "foo foo",
"C": "last part"
},
...
}
Where "crypto"
is json serialization of some cryptographic key.
Later in the code, I need to make something like this:
var keyOptions = CryptoProvider.RestoreFromJson(Configuration.GetSection("crypto"))
But Configuration.GetSection
return ConfigurationSection
instance. Is there a way to get raw json data behind it somehow?
I assumed that ConfigurationSection.Value
should do the trick, but for some reason it's always null
.
Here is an example impelementaion.
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;
}
}
If you want to get content of crypto
section, you can use
Configuration.GetSection("crypto").AsEnumerable()
(or for your example Configuration.GetSection("crypto").GetChildren()
may be useful).
But the result is not raw json. You need to convert it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With