According to http://blog.jsinh.in/asp-net-5-configuration-microsoft-framework-configurationmodel/, things have changed. However, I couldn't understand from that document how to read appSettings
keys. There's an example on reading from ini files though.
How do I avoid using the old System.Configuration.ConfigurationManager
to read AppSettings
key values from web.config?
You can access the config values through ConfigurationSettings. AppSettings["Your Key"].
AppSettings provide an easy way to access string values, based on a certain key. Take these appSettings for example: We can access this value by using this piece of code: As a side note: you will need to import the System.
Provides access to configuration files for client applications. This class cannot be inherited.
Add a json
file to your project root dir: config.json
{
"AppSettings": {
"TestKey" : "TestValue"
}
}
Create a new class
for config deserialization:
public class AppSettings
{
public string TestKey { get; set; }
}
In Startup.cs
:
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
// Setup configuration sources.
var builder = new ConfigurationBuilder()
.SetBasePath(appEnv.ApplicationBasePath)
.AddJsonFile("config.json")
.AddJsonFile($"config.{env.EnvironmentName}.json", true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
public void ConfigureServices(IServiceCollection services)
{
var builder = services.AddMvc();
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
}
Get the options in your controller
:
public HomeController(IOptions<AppSettings> settings)
{
var value = settings.Value.TestKey;
}
I'm not sure what's wrong with System.ConfigurationManager.AppSettings
[MSDN] as it still works in 4.5 & 4.6
But I think what you're asking for is System.Configuration.AppSettingsReader.GetValue()
[MSDN]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With