【发布时间】:2019-10-18 18:32:58
【问题描述】:
我正在尝试将 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 文件夹中
【问题讨论】:
-
很可能是因为 json 文件不在您的二进制文件所在的目录中。
-
是的。否则,
_configuration.GetSection("Section1:Prop1")如何正常工作? -
如果设置了 optional:false 会发生什么?我想你没有将 appsettings.json 文件复制到 bin 目录中,所以它从来没有真正读取你的文件。
-
@asawyer 没什么,和以前一样。我保证将设置文件复制到 bin 目录!
-
ConfigurationBuilder不会神奇地咳出Section1Model对象。您将获得一个通用的IConfigurationSection接口,其属性可通过索引器或GetChildren访问,但没有Value,因为这仅适用于标量。要将其绑定到普通的旧对象,请使用ConfigurationBinder.Get()或ConfgurationBinder.Bind()。 (通常,这是通过在ServiceCollection上调用适当的扩展方法来在幕后完成的,例如.AddOptions,但如果需要,您可以手动执行操作。)