davidwhitney / System.Configuration.Abstractions

Injectable, mockable, extensible, configuration for .NET
MIT License
42 stars 7 forks source link

Reading appsettings.json in .net core? #17

Closed roncanepa closed 6 years ago

roncanepa commented 6 years ago

I've successfully used the library in other projects and have now begun a new API project in .Net Core 2.x targeting the framework 4.6.1 where I'm reusing some of the previous functionality.

Note that I'm not very familiar with .net core yet so it could be that I'm doing something silly. I'm getting a "Calling code requested setting named 'Vendor.OurPlatform' but it was not in the config file" exception. I'm using v2.0.2.45 of Abstractions.

My appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {},
  "Vendor.OurPlatform": "AzureDev",
  "Vendor.VendorPlatform":  "Demo"
}

and it validates as proper json.

I have the following function:

        private OurPlatforms GetOurPlatform(IConfigurationManager manager)
        {
            return manager.AppSettings.AppSettingConvert<OurPlatforms>("Vendor.OurPlatform");
        }

As far as I can tell, the keys match (because I pasted them straight out of the web config of a project where this all works) and they're on the proper level in the json object.

Am I missing something obvious? I've tried about every combination of things I can think of with variations on the json structure, putting it in other files, and even reading up on ConfigurationManager. This issue here (https://github.com/Azure/azure-functions-core-tools/issues/33) seems to suggest that .net's ConfigurationManager can indeed read the appsettings.json file...

Though Core has its own configuration stuff, I'd prefer to keep using System.Configuration.Abstractions for this project due to a shared library...

Thanks.

roncanepa commented 6 years ago

I just figured it out. It won't read anything from appsettings.json. In my particular case, .NET Core targeting .NET framework 4.6.1, there will also be an app.config file in your project. You need to put your settings in there.

I tried it previously and it didn't work, but here's the key: You need to do a "clean" and then "rebuild", because otherwise the ApplicationName.exe.config file in your /bin gets cached and won't be updated with your keys.