ASP.NET Core:JSON配置GetSection返回null

时间:2017-05-15 07:01:08

标签: c# asp.net json configuration

我有一个文件appsettings.json,如下所示:

{
    "MyConfig": {
        "ConfigA": "value",
        "ConfigB": "value"
    }
}

在我的Startup.cs我正在构建我的IConfiguration

public ConfigurationRoot Configuration { get; set; }

public Startup(ILoggerFactory loggerFactory, IHostingEnvironment environment)
{
      var builder = new ConfigurationBuilder()
                     .SetBasePath(environment.ContentRootPath)
                     .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)                             
                     .AddEnvironmentVariables();

      Configuration = builder.Build();
}

public void ConfigureServices(IServiceCollection services)
{
      //GetSection returns null...
      services.Configure<MyConfig>(Configuration.GetSection("MyConfig"));
}

但是Configuration.GetSection("MyConfig")总是返回null,尽管我的JSON文件中存在该值。 Configuration.GetSection("MyConfig:ConfigA")工作正常。

我做错了什么?

4 个答案:

答案 0 :(得分:1)

请参阅以下代码

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        var config = Configuration.GetSection("MyConfig");
        // To get the value configA
        var value = config["ConfigA"];

        // or direct get the value
        var configA = Configuration.GetSection("MyConfig:ConfigA");

        var myConfig = new MyConfig();
        // This is to bind to your object
        Configuration.GetSection("MyConfig").Bind(myConfig);
        var value2 = myConfig.ConfigA;
    }
}

答案 1 :(得分:1)

这对我有用。

public void ConfigureServices(IServiceCollection services)  
{  
     services.Configure<MyConfig>(con=> Configuration.GetSection("MyConfig").Bind(con));  
}

答案 2 :(得分:1)

我刚遇到这个。如果使用完整路径,则这些值在那里,但是我需要将它们自动绑定到配置类。

.Bind(config)在我向类的属性添加自动属性访问器后开始工作。即

public class MyAppConfig {
  public string MyConfigProperty { get; set;} //this works
  public string MyConfigProperty2; //this does not work
}

答案 3 :(得分:0)

对于遇到此问题并试图在测试项目中执行相同操作的任何人,这对我来说是有效的:

other = config.GetSection("OtherSettings").Get<OtherSettings>();