JSON Configuration in full .NET Framework Console App

27.7k Views Asked by At

I have a Console App targeting .NET 4.7.1. I'm trying to use .net core like configuration in my .Net Framework app. My `App.config is:

<configuration>
  <configSections>
    <section name="configBuilders" type="System.Configuration.ConfigurationBuildersSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" restartOnExternalChanges="false" requirePermission="false" />
  </configSections>
  <configBuilders>
    <builders>
    <add name="SimpleJson"
         jsonFile="config.json"
         optional="false"
         jsonMode="Sectional"
         type="Microsoft.Configuration.ConfigurationBuilders.SimpleJsonConfigBuilder, Microsoft.Configuration.ConfigurationBuilders.Json, Version=1.0.0.0, Culture=neutral" /></builders>
  </configBuilders>

And I have a file config.json which has property "Copy Always" set to True. config.json looks like:

  {
  "appSettings": {
    "setting1": "value1",
    "setting2": "value2",
    "complex": {
      "setting1": "complex:value1",
      "setting2": "complex:value2"
    }
  },

  "connectionStrings": {
    "mySpecialConnectionString": "Dont_check_connection_information_into_source_control"
  }
}

Then, in my main method, I try to read a config value like:

var config = ConfigurationManager.AppSettings

However, the value of config is always null. I tried the following:

  1. Tried changing jsonFile to ~/config.json;
  2. Tried giving a very basic key-value (flat) json config while setting jsonMode to default value of flat;

But, can't get the config to work. How can I fix this issue?

5

There are 5 best solutions below

2
On

I did this as well some time ago but it was not just an one-liner. You can use the Microsoft Nuget Packages Microsoft.Extensions.Configuration & Microsoft.Extensions.Configuration.Json and setup up your own ConfigurationBuilder.

Take a look at this article, I think you should get through with it.

0
On

I'm not sure how are the defaults working right now, but i'll show you how i loaded my config files in .net core.

After CreateDefaultBuilder and before UseStartup add ConfigureAppConfiguration method like that:

 public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((hostingContext, config) =>
                {
                    //HostingEnvironment = hostingContext.HostingEnvironment;

                    //config.SetBasePath(HostingEnvironment.ContentRootPath);
                    var workingDirectory = AppContext.BaseDirectory; // HostingEnvironment.ContentRootPath // Directory.GetCurrentDirectory()
                    foreach (var file in Directory.GetFiles(workingDirectory, "*_config.json"))
                    {
                        config.AddJsonFile(file);//);Path.GetFileName(file));
                    }
                })
                .UseStartup<Startup>();

In your case, if your config is not loaded:

config.AddJsonFile(Path.Combine(workingDirectory, "config.json"));

This adds .config file to the applicication. In ConfigureServices method we can access this configurations by sections and fill some class properties with this values.

services.Configure<CommonAppSettings>(this.Configuration.GetSection("appSettings"));

Direct access:

var value1 = this.Configuration.GetSection("appSettings").GetValue(typeof(string), "setting1", "defaultValueIfNotFound");

Connection string:

//I'm not sure about "ConnectionStrings" section case sensitivity.
var connectionString = this.Configuration.GetConnectionString("mySpecialConnectionString");

Helpful link: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.1

0
On

Look at the example in source code

You should add in your config file section

<appSettings configBuilders="SimpleJson">
<add key="AppConfiguration:Key1" value="will be replaced by value in json file" />
</appSettings>

And remove jsonMode="Sectional" attribute.

You can access your value using

var key1 = ConfigurationManager.AppSettings["AppConfiguration:Key1"];
0
On
  • The main thing I see omitted from your question is specifying the "configBuilders" attribute in your web.config file's "appSettings" element:<appSettings configBuilders="SimpleJson">
  • I do not think you have to remove the jsonMode="Sectional" attribute.
  • I do not think you have to configure set "Copy Always" to True for config.json.

This is the code that works for me:

<configBuilders>
    <builders>
    <add name="SimpleJson" jsonFile="~\developer_config.json" optional="false" jsonMode="Sectional" type="Microsoft.Configuration.ConfigurationBuilders.SimpleJsonConfigBuilder, Microsoft.Configuration.ConfigurationBuilders.Json, Version=1.0.0.0, Culture=neutral" />
    </builders>
</configBuilders>
<appSettings configBuilders="SimpleJson">
...
</appSettings>
5
On

If you want to use config json files as in .Net Core, you can install NuGet packages Microsoft.Extensions.Configuration and Microsoft.Extensions.Configuration.Json and then initialize the configuration

IConfigurationRoot configuration = new ConfigurationBuilder()
.AddJsonFile("config.json", optional: true)
.Build();

After this you can use configuration as in .Net Core. For example:

{
  "myConfig": {
    "item1": "config options"
  }
}

For this json you will call:

var configItem = configuration["myConfig:item1"];