【问题标题】:Unable to read data afrom appsettings.json无法从 appsettings.json 读取数据
【发布时间】:2018-09-15 18:13:37
【问题描述】:

我确定我有一些基本错误,但我无法发现它,抱歉。进入启动代码表明 appsettings.json 已正确加载,但测试类随后为配置类变为空。

启动:

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"
  }
}

我错过了什么?

【问题讨论】:

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


    【解决方案1】:

    在使用 serives.Configure&lt;T&gt;() 配置选项之前,在 ConfigureServices 方法中添加以下行。要使用选项功能,您必须启用它。

    services.AddOptions();

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多