Home > Blockchain >  Get value from appsettings.json from array of objects
Get value from appsettings.json from array of objects

Time:05-14

We know that we can get values from json with the IConfiguration class with the GetSection method or simply with configuration["Serilog:Properties:ApplicationName"]; in case of array with configuration.GetSection("Serilog.Enrich").Get<string[]>()

But I don't know how to retrieve the value of "serverUrl" key that is nested in the first node of the WriteTo array

"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"
        }
      }
    ]
  }

Any suggestion?

CodePudding user response:

try this

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

or using c# classes

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

classes

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

    public Args Args { get; set; }
}

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