Casey Crookston
Casey Crookston

Reputation: 13945

Get values from appsettings.json in .net core 3.1

What I'm trying to do should be simple but I can not get it to work!!

My appsettings.json file:

{
  "AppSettings": {
    "myKey": "myValue",
  }
}

And then:

var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
var myValue = config["myKey"];

myValue is null.

I also tried:

var builder = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddEnvironmentVariables();
IConfiguration config = builder.Build();

var myValue = config.GetSection("myKey");

But again, myValue is null.

Upvotes: 7

Views: 15216

Answers (2)

Vimal Maradiya
Vimal Maradiya

Reputation: 1

You have to write var myValue = config["AppSettings:myKey"]; instead of var myValue = config.GetSection("myKey");, Because myKey is inside of AppSettings:myKey.

Upvotes: 0

Gabriel Cappelli
Gabriel Cappelli

Reputation: 4170

In your appsettings.json myKey is inside an AppSettings object.

That whole object is being loaded, so you'll need to reference it:

var myValue = config["AppSettings:myKey"];

Reference: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1#hierarchical-configuration-data

Upvotes: 7

Related Questions