Pea*_*ler 8 c# as-operator asp.net-core
我正在尝试检索应用程序内的配置。
我已将 IConfiguration 传递到需要提取一些设置的服务类中。
这个类看起来有点像这样:
private IConfiguration _configuration;
public Config(IConfiguration configuration)
{
_configuration = configuration;
}
public POCO GetSettingsConfiguration()
{
var section = _configuration.GetSection("settings") as POCO;
return section;
}
Run Code Online (Sandbox Code Playgroud)
在调试中,我可以看到 _configuration 确实包含设置,但我的“部分”只是返回为 null。
我知道我可以尝试设置要在启动时创建的 Poco,然后作为依赖项注入,但由于设置的原因,如果可能的话,我宁愿在与注入的 IConfiguration 不同的类中进行操作。
我的 appsettings.json 具有以下值:
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"settings": {
"Username": "user",
"Password": "password",
"Domain": "example.com",
"URL": "http://service.example.com"
}
}
Run Code Online (Sandbox Code Playgroud)
我的 poco 类如下所示:
public class POCO
{
public string URL { get; set; }
public string Username { get; set; }
public SecureString Password { get; set; }
public string Domain { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
Chr*_*att 10
您需要使用:
var section = _configuration.GetSection("settings").Get<POCO>();
Run Code Online (Sandbox Code Playgroud)
返回的GetSection只是一个字符串字典。您不能将其投射到 POCO 类。
IConfiguration并IConfigurationSection有一个扩展方法Bind用于此目的:
var poco = new POCO();
_configuration.GetSection("settings").Bind(poco);
Run Code Online (Sandbox Code Playgroud)
或者只是获取
var poco = _configuration.GetSection("settings").Get(typeof(POCO));
Run Code Online (Sandbox Code Playgroud)
或通用获取
var poco = _configuration.GetSection("settings").Get<POCO>();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6274 次 |
| 最近记录: |