appsettings.json
configuration management
.NET Core
application settings
JSON parsing

how to get value from appsettings.json

Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms

Introduction

In .NET Core and .NET 5+, appsettings.json replaces the older web.config and app.config XML files for application configuration. The framework provides a built-in configuration system that reads appsettings.json at startup and makes values available through dependency injection. You access values using IConfiguration for raw key-value lookups or the strongly-typed Options pattern for structured settings.

The appsettings.json File

json
1{
2  "ConnectionStrings": {
3    "DefaultConnection": "Server=localhost;Database=MyApp;Trusted_Connection=True;"
4  },
5  "Logging": {
6    "LogLevel": {
7      "Default": "Information"
8    }
9  },
10  "AppSettings": {
11    "ApiKey": "abc123",
12    "MaxRetries": 3,
13    "BaseUrl": "https://api.example.com",
14    "Features": {
15      "EnableCaching": true,
16      "CacheDurationMinutes": 30
17    }
18  }
19}

Method 1: IConfiguration (Direct Access)

Inject IConfiguration and read values using section-colon-key notation:

csharp
1public class HomeController : Controller
2{
3    private readonly IConfiguration _config;
4
5    public HomeController(IConfiguration configuration)
6    {
7        _config = configuration;
8    }
9
10    public IActionResult Index()
11    {
12        // Read a simple value
13        string apiKey = _config["AppSettings:ApiKey"];  // "abc123"
14
15        // Read a nested value
16        bool caching = _config.GetValue<bool>("AppSettings:Features:EnableCaching");  // true
17
18        // Read with a default fallback
19        int retries = _config.GetValue<int>("AppSettings:MaxRetries", 5);  // 3
20
21        // Read connection string (shortcut)
22        string connStr = _config.GetConnectionString("DefaultConnection");
23
24        return View();
25    }
26}

The colon : separates nested sections. GetValue<T> handles type conversion automatically.

Bind a configuration section to a strongly-typed class:

csharp
1// 1. Define the settings class
2public class AppSettings
3{
4    public string ApiKey { get; set; }
5    public int MaxRetries { get; set; }
6    public string BaseUrl { get; set; }
7    public FeatureSettings Features { get; set; }
8}
9
10public class FeatureSettings
11{
12    public bool EnableCaching { get; set; }
13    public int CacheDurationMinutes { get; set; }
14}
csharp
// 2. Register in Program.cs (or Startup.cs)
builder.Services.Configure<AppSettings>(
    builder.Configuration.GetSection("AppSettings"));
csharp
1// 3. Inject IOptions<T> in your class
2public class MyService
3{
4    private readonly AppSettings _settings;
5
6    public MyService(IOptions<AppSettings> options)
7    {
8        _settings = options.Value;
9    }
10
11    public void DoWork()
12    {
13        Console.WriteLine(_settings.ApiKey);           // "abc123"
14        Console.WriteLine(_settings.MaxRetries);       // 3
15        Console.WriteLine(_settings.Features.EnableCaching);  // true
16    }
17}

Method 3: Bind to a Class Manually

csharp
1// In Program.cs or a service
2var settings = new AppSettings();
3builder.Configuration.GetSection("AppSettings").Bind(settings);
4
5// Or use Get<T>()
6var settings = builder.Configuration
7    .GetSection("AppSettings")
8    .Get<AppSettings>();

Environment-Specific Settings

.NET automatically loads environment-specific overrides:

 
appsettings.json                    ← base settings
appsettings.Development.json        ← overrides for Development
appsettings.Production.json         ← overrides for Production
json
1// appsettings.Development.json
2{
3  "AppSettings": {
4    "ApiKey": "dev-key-123",
5    "BaseUrl": "https://dev-api.example.com"
6  }
7}

The environment is determined by the ASPNETCORE_ENVIRONMENT environment variable. Later files override earlier ones — only the keys you specify are overridden, not the entire section.

Reading Arrays

json
{
  "AllowedHosts": ["example.com", "api.example.com", "admin.example.com"]
}
csharp
1// Access by index
2string first = _config["AllowedHosts:0"];  // "example.com"
3
4// Bind to a list
5var hosts = _config.GetSection("AllowedHosts").Get<List<string>>();

IOptionsSnapshot vs IOptionsMonitor

csharp
1// IOptions<T> — singleton, read once at startup
2public MyService(IOptions<AppSettings> options)
3
4// IOptionsSnapshot<T> — scoped, re-reads per request (good for web apps)
5public MyService(IOptionsSnapshot<AppSettings> options)
6
7// IOptionsMonitor<T> — singleton but detects changes via OnChange callback
8public MyService(IOptionsMonitor<AppSettings> monitor)
9{
10    monitor.OnChange(newSettings =>
11    {
12        Console.WriteLine($"Settings changed: {newSettings.ApiKey}");
13    });
14}

Use IOptionsSnapshot when you want updated values per request without restarting. Use IOptionsMonitor for long-running services that need to react to config changes.

Reading in Program.cs (Before DI)

csharp
1var builder = WebApplication.CreateBuilder(args);
2
3// Access configuration before building the app
4string apiKey = builder.Configuration["AppSettings:ApiKey"];
5
6// Or bind to a class
7var settings = builder.Configuration
8    .GetSection("AppSettings")
9    .Get<AppSettings>();

Common Pitfalls

  • Null values: _config["NonExistent:Key"] returns null, not an exception. Always check for null or use GetValue<T>("key", defaultValue) with a fallback.
  • Case sensitivity: Configuration keys are case-insensitive in .NET. _config["appsettings:apikey"] works the same as _config["AppSettings:ApiKey"].
  • Secrets in appsettings.json: Never store passwords or API keys in appsettings.json for production. Use User Secrets (dotnet user-secrets), environment variables, or Azure Key Vault instead.
  • Forgetting to register Options: IOptions<T> injection fails with a DI error if you forget builder.Services.Configure<T>(section) in Program.cs.
  • IOptions is singleton: IOptions<T> reads the value once and caches it forever. If you edit appsettings.json at runtime, use IOptionsSnapshot<T> or IOptionsMonitor<T> to pick up changes.

Summary

  • Use IConfiguration["Section:Key"] for quick, one-off value access
  • Use the Options pattern (IOptions<T>) for structured, type-safe settings
  • Connection strings have a shortcut: _config.GetConnectionString("Name")
  • Environment-specific files (appsettings.{Environment}.json) override base settings automatically
  • Use IOptionsSnapshot<T> for per-request reload or IOptionsMonitor<T> for change notifications
  • Never store secrets in appsettings.json — use User Secrets or environment variables

Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms