How to change App.config to json config file in .Net Core

Serhii Shemshur picture Serhii Shemshur · Jul 27, 2016 · Viewed 11k times · Source

my project uses App.config to read config property. Example: ConfigurationManager.AppSettings["MaxThreads"] Do you know of a library which I can use to read config from json. Thanks.

Answer

Sock picture Sock · Jul 27, 2016

The ConfigurationManager static class is not generally available in ASP.NET Core. Instead you should use the new ConfigurationBuilder system and strongly typed configuration.

For example, by default, a configuration is built up in your Startup class using something similar to the following:

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();
    Configuration = builder.Build();
}

This will load configuration from the appsettings.json file and append the keys the configuration root. If you have an appsettings file like the following:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
    "Default": "Debug",
    "System": "Information",
    "Microsoft": "Information"
    }
  },
  "ThreadSettings" : {
     "MaxThreads" : 4
  }
}

Then you can then create a strongly typed ThreadSettings class similar to the following:

public class ThreadSettings
{
    public int MaxThreads {get; set;}
}

Finally, you can bind this strongly typed settings class to your configuration by adding a Configure method to your ConfigureServices method.

using Microsoft.Extensions.Configuration;
public void ConfigureServices(IServiceCollection services)
{
    services.Configure<ThreadSettings>(Configuration.GetSection("ThreadSettings"));
}

You can then inject and access your settings class from anyother place by injecting it into the constructor. For example:

public class MyFatController
{
    private readonly int _maxThreads;
    public MyFatController(ThreadSettings settings)
    {
        maxThreads = settings.MaxThreads;
    }
}

Finally, if you really need access to the underlying configuration you can also inject that in ConfigureServices to make it available in your classes.

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton(Configuration);
}

You can read more about configuration on the docs or on various blogs