Configuration.GetSection always returns null

前端 未结 9 1072
借酒劲吻你
借酒劲吻你 2020-12-16 09:01

Every time I call Configuration.GetSection, the Value property of the returned object is always null.

My Startup constructor

相关标签:
9条回答
  • 2020-12-16 09:28
    1. Right-click on appsettings.json and go to Properties.
    2. Select Copy to output directory = Copy always.
    0 讨论(0)
  • 2020-12-16 09:33

    Try add ConfigurationProvider to ConfigurationBuilder.

    App configuration is provided from:

    • appsettings.json using the File Configuration Provider.
    • appsettings.{Environment}.json using the File Configuration Provider.
    0 讨论(0)
  • 2020-12-16 09:36

    Just modify your ConfigureServices method to be like following:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddOptions();
    
        services.Configure<SqliteSettings>(Configuration.GetSection("SqliteSettings"));
    
        services.AddMvc();
    }
    

    and it should work.

    0 讨论(0)
  • 2020-12-16 09:38

    According to the Microsoft Docs: "When GetSection returns a matching section, Value isn't populated. A Key and Path are returned when the section exists."

    If you want to see the values of that section you will need to call the GetChildren() method: Configuration.GetSection("SqliteSettings").GetChildren();

    Or you can use: Configuration.GetSection("SqliteSettings").Get<SqliteSettings>(). The JSON does not need to have the same amount of properties to match. Unmatched nullable properties will be set to null and non-nullable unmatched properties will be set to their default value (e.g. int will be set to 0).

    0 讨论(0)
  • 2020-12-16 09:41

    This worked for me in a console application:

    var connectionString = config["ConnectionStrings:DefaultConnection"]
    
    0 讨论(0)
  • 2020-12-16 09:41

    If you have an appsettings.Development.json file, make sure the "ConnectionStrings:DefaultConnection" settings are the same in both the appsettings.Development.json and appsettings.json files.

    0 讨论(0)
提交回复
热议问题