简体   繁体   中英

Configuration.GetSection(“SectionName”) is always null when using manually added settings.json file to dotnet core console app

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?

PS: I promise the settings file is copied to the bin folder

ConfigurationBuilder only returns generic IConfiguration instances. If you want a strongly typed model out of that, it has to be bound first. There are several ways of doing that -- Microsoft's own implementation lives in Microsoft.Extensions.Configuration.Binder . This then gives you access to the static class ConfigurationBinder in several ways with extension methods on IConfiguration :

var model = _configuration.GetSection("Section1").Get<Section1Model>();

Oddly enough there's no extension method for directly getting a section into an object, but it would be easy enough to write one.

If you're using dependency injection ( Microsoft.Extensions.DependencyInjection , Microsoft.Extensions.Options.ConfigurationExtensions ) there'll be a .Configure<Section1Model>() extension method to register this binding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM