我确定我有一些基本错误,但我无法发现它,抱歉。进入启动代码表明 appsettings.json 已正确加载,但测试类随后为配置类获取 null。
启动:
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"));
}
}
配置测试器:
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
}
}
环境配置:
public class EnvironmentConfig
{
public string Name;
}
appSettings.json:
{
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Warning"
}
},
"Console": {
"LogLevel": {
"Default": "Warning"
}
}
},
"EnvironmentConfig": {
"Name": "develop"
}
}
我错过了什么?
最佳答案
在使用 serives.Configure<T>()
配置选项之前,在您的 ConfigureServices 方法中添加以下行.要使用选项功能,您必须启用它。
services.AddOptions();
关于c# - 无法从 appsettings.json 读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52347551/