I am trying to add settings.json file manually to a .net core 2.1 console application. So I add these NuGet packages to the project:
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.FileExtensions
Microsoft.Extensions.Configuration.Json
and create the appsettings.json file like this:
{
"Section1": {
"Prop1": "value",
"Prop2": 300
}
}
Finally, I try to get value from the settings file like this:
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
_configuration = builder.Build();
var section = _configuration.GetSection("Section1");//section.Value is null
var test = _configuration.GetSection("Section1:Prop1");//it returns the proper value
var model = section as Section1Model;
But, section.Value is null and in consequence, the model is null. If I try to get values like _configuration.GetSection("Section1:Prop1") it returns the correct value. Also, If I call _configuration.GetSection("Section1).GetChildren() it returns a collection of settings. What I did wrong?
P.S: I promise the settings file is copied to the bin folder