从对象数组中获取 appsettings.json 的值

Get value from appsettings.json from array of objects

我们知道我们可以使用 IConfiguration class 和 GetSection 方法从 json 获取值,或者在数组 configuration.GetSection("Serilog.Enrich").Get<string[]>()[= 的情况下简单地使用 configuration["Serilog:Properties:ApplicationName"]; 14=]

但我不知道如何检索嵌套在 WriteTo 数组第一个节点中的“serverUrl”键的值

"Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning",
        "Serilog": "Warning"
      }
    },
    "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
    "Properties": {
      "ApplicationName": "MyApp"
    },
    "WriteTo": [
      {
        "Name": "Seq",
        "Args": {
          "serverUrl": "http://localhost:5341"
        }
      }
    ]
  }

有什么建议吗?

试试这个

var serverUrl = configuration.GetSection("Serilog").GetSection("WriteTo")
.Get<Dictionary<string,Dictionary<string,string>>[]>()[0]["Args"]["serverUrl"]; 

或使用 c# 类

var serverUrl = configuration.GetSection("Serilog").GetSection("WriteTo")
.Get<WriteTo[]>()[0].Args.serverUrl; 

public partial class WriteTo
{
    public string Name { get; set; }

    public Args Args { get; set; }
}

public partial class Args
{
    public Uri serverUrl { get; set; }
}