7

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?

Jamie Dunstan
  • 3,725
  • 2
  • 24
  • 38
Old Geezer
  • 14,854
  • 31
  • 111
  • 198
  • 1
    Possible duplicate of [How can I read/write app.config settings at runtime without using user settings?](https://stackoverflow.com/questions/3638754/how-can-i-read-write-app-config-settings-at-runtime-without-using-user-settings) – Matt Sep 26 '19 at 10:37

3 Answers3

7

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;
}
Cristi Pufu
  • 9,002
  • 3
  • 37
  • 43
1

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]

Dave Bry
  • 122
  • 1
  • 12
  • 1
    Under `References`, I added `System.Configuration (1.0.0)` to DNX 4.5.1. However, I still get "The type or namespace 'Configuration' does not exist in the namespace 'System' (are you missing an assembly or reference?)" – Old Geezer Dec 15 '15 at 01:00
0

You can get values using ["setting-key"] syntax:

IConfiguration _configuration;
...
var setting = _configuration["SomeKey"];

Or you can parse config section to some custom object as follows:

IConfiguration configuration;
...
var myCustomObject = configuration.GetSection("SomeSection").Get<MyCustomObject>();

Pay attention - in second approach you should reference the following MS Nugget packages:

  1. Microsoft.Extensions.Configuration
  2. Microsoft.Extensions.Configuration.Builder
  3. Microsoft.Extensions.Configuration.Json
Mark
  • 51
  • 1
  • 2