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

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

+5
source share
1 answer

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

For example, by default, a configuration is created 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 the configuration from the appsettings.json file and add the keys to the configuration root. If you have an appsettings file, for example:

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

Then you can 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 the Configure method to your ConfigureServices method.

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

Then you can enter an access class and access it from anywhere else by entering it in the constructor. For instance:

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

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

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

You can learn more about configuration on docs or on various blogs.

+13
source

All Articles