我正在尝试将 settings.json 文件手动添加到 .net core 2.1 控制台应用程序。所以我将这些 NuGet 包添加到项目中:
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.FileExtensions
Microsoft.Extensions.Configuration.Json
并像这样创建 appsettings.json
文件:
{
"Section1": {
"Prop1": "value",
"Prop2": 300
}
}
最后,我尝试像这样从设置文件中获取值:
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;
但是,section.Value
为 null
,因此 model
为 null
。如果我尝试获取像 _configuration.GetSection("Section1:Prop1")
这样的值,它会返回正确的值。此外,如果我调用 _configuration.GetSection("Section1).GetChildren()
,它会返回一组设置。我做错了什么?
P.S: 我保证将设置文件复制到bin文件夹
最佳答案
ConfigurationBuilder
只返回通用 IConfiguration
实例。如果你想要一个强类型模型,它必须先绑定(bind)。有几种方法可以做到这一点——微软自己的实现在 Microsoft.Extensions.Configuration.Binder
中。 .然后,这使您可以访问静态类 ConfigurationBinder
在 IConfiguration
上以多种方式使用扩展方法:
var model = _configuration.GetSection("Section1").Get<Section1Model>();
奇怪的是,没有直接将一个部分放入对象的扩展方法,但写一个很容易。
如果您使用依赖注入(inject)(Microsoft.Extensions.DependencyInjection
,Microsoft.Extensions.Options.ConfigurationExtensions
),将会有一个.Configure<Section1Model>()
注册此绑定(bind)的扩展方法。
关于c# - Configuration.GetSection ("SectionName") 在使用手动添加的 settings.json 文件到 dotnet 核心控制台应用程序时始终为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58440132/