appsettings.json in ASP.net Core 2.0 Preview configuration GetSection null

前端 未结 3 1049
情歌与酒
情歌与酒 2021-02-13 09:28

I was trying to call GetSection from injected configuration in the Startup.cs. The Value was null, while indexer to a concret

3条回答
  •  日久生厌
    2021-02-13 10:19

    I found AspNetCore 2.0 to be so much simpler than 1.x in terms of configuration.

    If you put a breakpoint in the Startup(IConfiguration configuration) constructor, you'll notice that the configuration variable has about 5 providers.

    The JsonConfigurationProvider is the provider you're interested in for the appsettings.json file, but you will probably notice that the Data property has a Count=0. That is most likely due to the fact that your application is looking for the appsettings.json file in the directory specified in the JsonConfigurationProvider.Source.FileProvider.Root (which is by default wwwroot).

    All I did was add an MSBuild task in the .csproj file as follows:

    
    

    And that seemed to work perfectly.

    This is obviously useful during local development only. However, the general practice these days is never to have configuration in a file in the first place, especially since it will end up being part of your repo history. Instead, when deploying your app, the two common practices these days are using environment variables to override your values, or even better using a key/value store like consul.

    Moreover, I see a whole bunch of fancy examples online on how to use the services.Configure<>() which is fine, but the Startup.cs already uses DI to inject values to IConfiguration configuration. That means that IConfiguration is already registered in .NET core's IoC Container, so that essentially means you can already use IConfiguration in any other class in your app like so:

    public JobsRepository(IConfiguration configuration)
    {
        this.configA = configuration.GetSection("MyConfig:ConfigA").Value;
    }
    

提交回复
热议问题