我想使用强类型类访问appsettings.json文件(可能还有其他配置文件)。 在.NET Core 1(例如https://weblog.west-wind.com/posts/2016/may/23/strongly-typed-configuration-settings-in-aspnet-core)中有很多关于这样做的信息,但是几乎没有关于.NET Core 2的信息。
此外,我正在构建一个控制台应用程序,而不是ASP.NET。
似乎配置API在.NET Core 2中已经完全改变了。我无法解决它。任何人?
编辑:我想也许Core 2文档还没有赶上。示例:https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.configuration.configurationbinder?view=aspnetcore-2.0表示,您认为ConfigurationBinder存在于.NET Core 2中,但Microsoft.Extensions.Configuration和Microsoft.Extensions.Options的对象浏览器搜索没有显示任何内容。我使用了NuGet控制台
答案 0 :(得分:6)
感谢Martin Ullrich的观察,这导致了解决方案。这里有几件事情在发挥作用:
Microsoft.Extensions.Configuration
包会安装子命名空间DLL。事实上,NuGet Gallery中有很多软件包(参见here)。 NuGet控制台不会告诉您具体使用哪些DLL,但是一旦安装完毕,您就可以在解决方案浏览器中看到它们:
总而言之,解决方案是:
第一个提供.Bind
方法,第二个提供.SetBasePath
和.AddJsonFile
方法。
一旦我完善它,我会在一天左右添加最终代码。
编辑:
public class TargetPhoneSetting {
public string Name { get; set; } = "";
public string PhoneNumber { get; set; } = "";
}
public class AppSettings {
public List<TargetPhoneSetting> TargetPhones { get; set; } = new List<TargetPhoneSetting>();
public string SourcePhoneNum { get; set; } = "";
}
public static AppSettings GetConfig() {
string environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var builder = new ConfigurationBuilder()
.SetBasePath(System.IO.Directory.GetCurrentDirectory())
.AddYamlFile("appsettings.yml", optional: false)
;
IConfigurationRoot configuration = builder.Build();
var settings = new AppSettings();
configuration.Bind(settings);
return settings;
}
请注意,上面的代码实际上是针对YAML配置文件的。您需要调整加载YAML以使用JSON的单行。我没有测试过这些,但它们应该很接近:
JSON:
{
"SourcePhoneNum": "+61421999999",
"TargetPhones": [
{
"Name": "John Doe",
"PhoneNumber": "+61421999888"
},
{
"Name": "Jane Doe",
"PhoneNumber": "+61421999777"
}
]
}
YAML:
SourcePhoneNum: +61421999999
TargetPhones:
- Name: John Doe
PhoneNumber: +61421999888
- Name: Jane Doe
PhoneNumber: +61421999777