【发布时间】:2023-04-10 22:52:01
【问题描述】:
我有一个带有以下值的 appsettings.json 文件
{
"MailOptions":
{
"Username": "ruskin",
"Password": "password"
}
}
当我通过ConfigurationBuilder 读取它时,我只能通过configuration["MailSettings:Username"] 访问这些值。我想获取整个 MailOptions 字符串,有什么办法吗?我不想使用 Json 来解析文件等...我想坚持使用配置生成器。
我希望configuration.GetSection("MailOptions") 可以工作?它只是返回null。
我的尝试
SomeSection aSection = new SomeSection();
ServiceCollection serviceCollection = new ServiceCollection();
serviceCollection.Configure<SomeSection>(options => configuration.GetSection("SomeSection").Bind(aSection));
var someSection = serviceCollection.BuildServiceProvider().GetService<IOptions<SomeSection>>();
// aSection is instantiated but no values in it
// someSection is null
我的 appsettings.json
{
"SomeSection": {
"UserName": "ruskin",
"Password": "dantra"
}
}
还有我的 POCO 课
public class SomeSection
{
public string UserName { get; set; }
public string Password { get; set; }
}
【问题讨论】:
-
这篇关于
Strongly Typed Configuration Settings in ASP.NET Core的好文章提供了如何在.NET Core weblog.west-wind.com/posts/2016/may/23/… 中使用设置的清晰示例
标签: json .net-core appsettings