15

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?

Imre Pühvel
  • 4,468
  • 1
  • 34
  • 49
kovac
  • 4,945
  • 9
  • 47
  • 90

5 Answers5

14

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"];
Chad Hedgcock
  • 11,125
  • 3
  • 36
  • 44
  • 4
    But these 2 nuget packages depends on .netCore 3.1 will they work for .net framework 4.6 apps? – user1066231 Jun 17 '20 at 09:55
  • 2
    For Net Framework you must use version 1.1.2 since newer versions do not support Net Framework: https://www.nuget.org/packages/Microsoft.Extensions.Configuration.Json/1.1.2 – Roland Pihlakas Aug 01 '20 at 20:30
  • 4
    Since you need to use a deprecated version of the Microsoft extensions, it probably means that this approach is not fully supported in .NET Framework by Microsoft anymore. Since the OP specifically asked for a .NET Framework solution, I down-voted this answer. – Jim K Aug 12 '21 at 15:31
  • 1
    I understand you are trying to evolve away from the app.config configuration and you have valid reasons to do that but I would say @JimK is right: the recommended way for .NET Framework projects is, as you had before, via Settings (app.config) which is an autogenerated type-safe class after you configure the settings in the project using the settings designer. It is quite trivial to work with and, more importantly, type-safe; something appsettings.json is not out of the box, i.e., you need to somehow parse it yourself. – Lucky Brain Sep 23 '21 at 15:29
  • You can use version 7 of these packages with Framework 4.6.2+. So this approach is now fully supported in .NET Framework. – Giorgos Betsos Aug 07 '23 at 12:37
3

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.

Waescher
  • 5,361
  • 3
  • 34
  • 51
  • 1
    I think that the whole idea is to use SimpleJsonConfigBuilder from [MicrosoftConfigurationBuilders](https://github.com/aspnet/MicrosoftConfigurationBuilders) but it seems it is not just "take it from the box". There is no test yet in this project for this case. There is SimpleJson_GetValue() and SimpleJson_GetAllValues() but both are empty. – Belurd Dec 04 '18 at 08:26
  • 2
    For Net Framework you must use version 1.1.2 since newer versions do not support Net Framework: https://www.nuget.org/packages/Microsoft.Extensions.Configuration.Json/1.1.2 – Roland Pihlakas Aug 01 '20 at 20:30
1
  • 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>
Paul Schroeder
  • 1,460
  • 1
  • 14
  • 21
0

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"];
-2

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

Obelixx
  • 117
  • 5