我有一个文件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")工作正常。
我做错什么了?

最佳答案

请参考下面的代码

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

关于c# - ASP.NET Core:JSON配置GetSection返回null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43973265/

10-14 10:41