16

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?

0

5 Answers 5

16

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"];
Sign up to request clarification or add additional context in comments.

5 Comments

But these 2 nuget packages depends on .netCore 3.1 will they work for .net framework 4.6 apps?
For Net Framework you must use version 1.1.2 since newer versions do not support Net Framework: nuget.org/packages/Microsoft.Extensions.Configuration.Json/…
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.
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.
You can use version 7 of these packages with Framework 4.6.2+. So this approach is now fully supported in .NET Framework.
5

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.

2 Comments

I think that the whole idea is to use SimpleJsonConfigBuilder from 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.
For Net Framework you must use version 1.1.2 since newer versions do not support Net Framework: nuget.org/packages/Microsoft.Extensions.Configuration.Json/…
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>

Comments

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

Comments

-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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.