简体   繁体   English

无法从appsettings.json读取数据

[英]Unable to read data afrom appsettings.json

I'm sure I've got something basic wrong but I can't spot it, sorry. 对不起,我确定我有一些基本错误,但我无法发现。 Stepping into the startup code suggests the appsettings.json is being correctly loaded, but the test class then gets null for the config class. 单步执行启动代码表明正在正确加载appsettings.json,但测试类的config类为null。

Startup: 启动:

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: 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: EnvironmentConfig:

public class EnvironmentConfig
{
    public string Name;

}

appSettings.json: appSettings.json:

{
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning"
      }
    }
  },
  "EnvironmentConfig": {
    "Name": "develop"
  }
}

What have I missed? 我错过了什么?

Add the following line in your ConfigureServices method before you configure your Options using serives.Configure<T>() . 在使用serives.Configure<T>()配置选项之前,在ConfigureServices方法中添加以下行serives.Configure<T>() To use the Options feature you have to enable it. 要使用“选项”功能,您必须启用它。

services.AddOptions();

When using IServiceCollection.Configure , the ConfigurationBinder class that ends up doing the work of binding the values in your appSettings.json file to your EnvironmentConfig class only binds against properties . 使用IServiceCollection.Configure ,最终将appSettings.json文件中的值绑定到EnvironmentConfig类的ConfigurationBinder仅绑定属性 That means all you have to do is change your public field to a public property : 这意味着您所要做的就是将您的公共领域更改为公共财产

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM