Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read an appSettings key

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?

like image 733
Old Geezer Avatar asked Dec 14 '15 15:12

Old Geezer


People also ask

How do I get appSettings value in console application?

You can access the config values through ConfigurationSettings. AppSettings["Your Key"].

What is appSettings in C #?

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.

What is the use of Configurationmanager appSettings?

Provides access to configuration files for client applications. This class cannot be inherited.


2 Answers

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;
}
like image 119
Cristi Pufu Avatar answered Oct 13 '22 16:10

Cristi Pufu


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]

like image 30
Dave Bry Avatar answered Oct 13 '22 16:10

Dave Bry