c# - 获取 ConfigurationSection 的初始 JSON 表示

标签 c# json asp.net-core asp.net-core-mvc appsettings

假设我们在 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/

相关文章:

c# - 如何使用 LINQ 将 <string,list<string>> 缩减为 <string,string>?

c# - 在 C# 中合并两个对象

python - 如何以 CSV 表格格式将原始数据源从 Google Big Query 导出到 R 服务器?

javascript - 特别是当我们必须在 2 个日期之间选择数据时,以下哪个 JSON 更适合使用?

c# - 检查状态生存时间是否未过期

asp.net - 使用两个 FK 时无法创建关系

c# - WPF:绑定(bind)到具有自定义行为的类的属性

javascript - 如何从angularjs http回调中查看json数据?

azure - Identity Server 4在部署到Azure应用服务时找不到证书

c# - 如何让 Scroll 与垂直方向的 Hub Control Windows Phone 8.1 应用程序一起工作