从 appsettings.json 读取 JSON 对象

Bab*_*fas 7 json configuration-files .net-core

TL;DR: 如何从 appsettings.json 读取复杂的 JSON 对象?

我有一个具有多种类型配置值的 .NET Core 2.x 应用程序。appsettings.json看起来像下面的片段,我试图将 的值ElasticSearch:MyIndex:mappings作为单个字符串或 JSON 对象读取。

{
"ConnectionStrings": {
    "redis": "localhost"
},
"Logging": {
    "IncludeScopes": false,
    "Debug": {
        "LogLevel": {
            "Default": "Warning"
        }
    },
    "Console": {
        "LogLevel": {
            "Default": "Warning"
        }
    }
},
"ElasticSearch": {
    "hosts": [ "http://localhost:9200" ],
    "MyIndex": {
        "index": "index2",
        "type": "mytype",
        "mappings": {
            "properties": {
                "property1": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "location": {
                    "type": "geo_point"
                },
                "code": {
                    "type": "string",
                    "index": "not_analyzed"
                }
            }
        }
    }
}
}
Run Code Online (Sandbox Code Playgroud)

我可以通过调用Configuration.GetValue<string>("ElasticSearch:MyIndex:index").

Configuration.GetSection Configuration.GetSection("ElasticSearch:MyIndex:mappings").Value为我提供了一个nullValue

Configuration.GetValue Configuration.GetValue<string>("ElasticSearch:MyIndex:mappings")也返回空值。这对我来说很有意义,因为基于上述尝试,该部分具有空值。

Configuration.GetValue Configuration.GetValue<JToken>("ElasticSearch:MyIndex:mappings")也返回空值。出于与上述相同的原因,这对我来说也很有意义。

chr*_*389 14

Dictionary<string,object> settings = Configuration
    .GetSection("ElasticSearch")
    .Get<Dictionary<string,object>>();
string json = JsonConvert.SerializeObject(settings);
Run Code Online (Sandbox Code Playgroud)

  • 尽管我希望这能起作用,但它引发了一个我无法解决的异常。有小费吗?也许现在在 .NET Core 3.1 中它的工作方式有所不同。System.ArgumentNullException:值不能为空。(参数“类型”)位于 System.Reflection.IntrospectionExtensions.GetTypeInfo(类型类型) (3认同)

Bab*_*fas 2

该解决方案最终比我最初尝试的任何方法都简单得多:将 appsettings.json 读取为任何其他 JSON 格式的文件。

JToken jAppSettings = JToken.Parse(
  File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "appsettings.json"))
);

string mapping = jAppSettings["ElasticSearch"]["MyIndex"]["mappings"];
Run Code Online (Sandbox Code Playgroud)

  • 这种方法有很多错误。如果您的设置被其他提供商覆盖,那么除非您遵循克里斯的回答,否则您将不会获得更新的值。 (3认同)
  • JToken是什么?你从哪里得到那个的?@babak-naffas (2认同)