How to read a single value from appsettings.json containing collections

54 views Asked by At

How can I read the URL value from the below shown appsettings.json file, without creating a class to load values through DI?

{
  "Serilog": {
    "WriteTo": [
      {
        "Name": "Seq",
        "Args": {
          "serverUrl": "http://localhost:1234"
        }
      }
    ]
  }
}

I tried the below snippet but it gives null.

var configurationBuilder = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json", optional: false)
    .AddJsonFile($"appsettings.{environmentName}.json", optional: true)
    .AddEnvironmentVariables();

IConfiguration _configuration = configurationBuilder.Build();
// 1st attempt
var url = _configuration.GetSection("Serilog").GetChildren().First()["Args::serverUrl"];
// 2nd attempt
var url = _configuration.GetValue<string>("Serilog:WriteTo:Args::serverUrl");
// 3rd attempt
var url = _configuration.GetSection("Serilog").GetChildren().First().GetSection("Args").GetValue("serverUrl");

None of those attempts worked.

There are some existing similar questions but none of them deal with getting a single value from collection.

2

There are 2 answers

1
Madax On BEST ANSWER

I'm sorry im not really familiar with "those words". English isn't my first language.

This here is your corrected 2nd try, without any dependencys/classes:

var configurationBuilder2 = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json", optional: false)
    .AddEnvironmentVariables();

IConfiguration _configuration2 = configurationBuilder2.Build();


var url2 = _configuration2.GetValue<string>("Serilog:WriteTo:0:Args:serverUrl");

You just had a little typo thus not accessing the key right.

1
sa-es-ir On

It's possible to get an item of an array in the configuration by setting the index. If you have only one item simply you can address it like this:

var url = builder.Configuration.GetValue<string>("Serilog:WriteTo:0:Args:serverUrl");