我确定我有一些基本的错误,但是我找不到它,对不起。进入启动代码表明appsettings.json已正确加载,但是测试类的config类为空。
启动:
public class Startup
{
public Startup(IConfiguration configuration)
{
var builder = new ConfigurationBuilder().AddJsonFile("appSettings.json");
Configuration = builder.Build();
}
public IConfiguration Configuration { get; set; }
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddSessionStateTempDataProvider();
services.AddSession();
services.Configure<EnvironmentConfig>(Configuration.GetSection("EnvironmentConfig"));
}
}
ConfigTester:
public class ConfigTester
{
private readonly IOptions<EnvironmentConfig> _environmentConfig;
public ConfigTester(IOptions<EnvironmentConfig> environmentConfig)
{
_environmentConfig = environmentConfig;
}
public string ConfigName()
{
return _environmentConfig.Value.Name; //_environmentConfig.Value is set, but Name is null
}
}
EnvironmentConfig:
public class EnvironmentConfig
{
public string Name;
}
appSettings.json:
{
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Warning"
}
},
"Console": {
"LogLevel": {
"Default": "Warning"
}
}
},
"EnvironmentConfig": {
"Name": "develop"
}
}
我错过了什么?
答案 0 :(得分:2)
在使用serives.Configure<T>()
配置“选项”之前,请在ConfigureServices方法中添加以下行。要使用“选项”功能,您必须启用它。
services.AddOptions();
答案 1 :(得分:1)
使用IServiceCollection.Configure
时,ConfigurationBinder
类最终完成了将appSettings.json
文件中的值绑定到EnvironmentConfig
类only binds against properties的工作。这意味着您要做的就是将您的公共字段更改为公共属性:
public class EnvironmentConfig
{
public string Name { get; set; }
}