.NET Core.NET Library using ConfigurationManager.AppSettings

I have a standard .NET 4.5.2 library that I have been using for many years. It has a dependency on ConfigurationManager.AppSettings, which means that I had to make sure that a specific set of parameters is in the appSettings section of my application or web.config files. Cannot pass these values. You must put them in the appSettings section.

I am launching a new project in .NET Core, but am targeting Net452 so that I can use several libraries (which still work fine).

I am facing a problem with this last library because I cannot figure out how to configure the settings correctly so that ConfigurationManager.AppSettings finds them.

Putting them in appSettings.json doesn't seem to work. Including them in the web.config file does not work either.

Is it possible?

Thanks!

+6
source share
1 answer

Yes, it is possible that you want, but you have to do it manually (I do not know if there is an easy way).

Suppose you have some settings in appsettings.json as shown below:

 { "AppSettings" : { "Setting1": "Setting1 Value" } } 

In the Startup.cs constructor set ConfigurationManager.AppSettings with the value:

  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(); // copy appsetting data into ConfigurationManager.AppSettings var appSettings = Configuration.GetSection("AppSettings").GetChildren(); foreach (var setting in appSettings.AsEnumerable()) { ConfigurationManager.AppSettings[setting.Key] = setting.Value; } } 

And get the value in the class library:

 var conStr = ConfigurationManager.AppSettings["Setting1"].ToString(); 
+6
source

All Articles