design

Working with Configuration in .NET Core: The Complete Guide

April 6, 2025

Tired of hardcoding settings? .NET Core's flexible configuration system lets you manage app settings like a pro! Here's everything you need to know:


🌟 Configuration Sources (Out of the Box)

✔ appsettings.json - Primary JSON config

✔ Environment variables - For deployment-specific settings

✔ Command-line arguments - Runtime overrides

✔ User secrets - Secure local development

✔ Azure Key Vault - Cloud secrets management


🛠 Basic Setup (Program.cs)

var builder = WebApplication.CreateBuilder(args);

// Access configuration
var config = builder.Configuration;

// Read values
var apiKey = config["ApiSettings:Key"]; 
var timeout = config.GetValue<int>("TimeoutSeconds");


📁 appsettings.json Deep Dive

{
  "Logging": {
    "LogLevel": {
      "Default": "Information"
    }
  },
  "ConnectionStrings": {
    "Default": "Server=localhost;Database=MyApp;"
  },
  "ApiSettings": {
    "Url": "https://api.example.com",
    "Key": "secret123",
    "Timeout": 30
  }
}


Access nested values:

var apiUrl = config["ApiSettings:Url"];
var dbConn = config.GetConnectionString("Default");


🔐 Environment-Specific Configs

FileWhen Usedappsettings.Development.jsonLocal devappsettings.Production.jsonLive env

.NET Core automatically loads the right file based on ASPNETCORE_ENVIRONMENT!


🕵️ Secret Management

For sensitive data (API keys, passwords):

  1. Enable User Secrets:


dotnet user-secrets init
dotnet user-secrets set "ApiSettings:Key" "super-secret"


Access like normal config:

var secretKey = config["ApiSettings:Key"]; 


🌍 Environment Variables

Powerful for containers/cloud:

export ApiSettings__Key=prod-secret-key


Note double underscore for nesting)

Access in code:

var envKey = config["ApiSettings:Key"];


💡 Pro Configuration Patterns

1. Strongly-typed config:

builder.Services.Configure<ApiSettings>(
    builder.Configuration.GetSection("ApiSettings"));


2. Validation with DataAnnotations:

public class ApiSettings
{
    [Required]
    public string Url { get; set; }
    
    [Range(1, 60)]
    public int Timeout { get; set; }
}


🚨 Common Pitfalls

❌ Hardcoding sensitive data

❌ Not using environment-specific configs

❌ Forgetting to call AddUserSecrets() in Development


🔥 Why .NET Core Config Rocks

✔ Unified access to multiple sources

✔ Environment-aware loading

✔ Hierarchical structure

✔ Runtime reload with reloadOnChange: true

Try it today! Replace just ONE hardcoded value with configuration.

#DotNetCore #Configuration #AppSettings #CSharp #BestPractices

0 + 4 =