public class Bar
{
public static readonly string Foo = ConfigurationManager.AppSettings[\"Foo\"];
}
In the .NET Framework 4.x, I can use the
Addition to answer from @MindingData. I like to map my settings recursively using Configuration.Bind(settings); so that I don't have to add every new section in ConfigureServices.
Example:
appsettings.json:
{
"MyConfiguration": {
"MyProperty": true
}
}
Settings class, properties must match appsettings.json names:
public class Settings
{
public MyConfigurationSettings MyConfiguration { get; set; }
public class MyConfigurationSettings
{
public bool MyProperty { get; set; }
}
}
Startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var settings = new Settings();
Configuration.Bind(settings);
services.AddSingleton(settings);
...
Can be used in controllers like this:
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly Settings _settings;
public ValuesController(Settings settings)
{
_settings = settings;
}
[HttpGet("GetValue")]
public ActionResult Get()
{
return Ok(_settings.MyConfiguration.MyProperty);
}
}