无法从appsettings.json

时间:2018-09-15 18:13:38

标签: c# asp.net-core .net-core asp.net-core-2.0

我确定我有一些基本的错误,但是我找不到它,对不起。进入启动代码表明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"
  }
}

我错过了什么?

2 个答案:

答案 0 :(得分:2)

在使用serives.Configure<T>()配置“选项”之前,请在ConfigureServices方法中添加以下行。要使用“选项”功能,您必须启用它。

services.AddOptions();

答案 1 :(得分:1)

使用IServiceCollection.Configure时,ConfigurationBinder类最终完成了将appSettings.json文件中的值绑定到EnvironmentConfigonly binds against properties的工作。这意味着您要做的就是将您的公共字段更改为公共属性

public class EnvironmentConfig
{
    public string Name { get; set; }
}