繁体   English   中英

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

[英]ASP.NET Core: JSON Configuration GetSection returns null

我有一个看起来像这样的文件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")工作得很好。

我究竟做错了什么?

对于遇到这种情况并试图在测试项目中做同样事情的人来说,这对我有用:

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

请参考以下代码

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

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

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

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

这对我有用。

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

我习惯于在我的类上使用字段而不是属性,我遇到了与您相同的问题......结果证明它们需要是属性,否则它不会完成类的值,而是将它们保留为默认值。

来自https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-6.0

一个选项类:

1. Must be non-abstract with a public parameterless constructor.
2. All public read-write properties of the type are bound.
3. Fields are not bound. In the preceding code, Position is not bound. The Position property is used so the string "Position" doesn't need to be hard coded in the app when binding the class to a configuration provider.

暂无
暂无

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

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