Configuration & Settings in .NET Core Web API

Configuration & Settings in .NET Core Web API

🎛️ Configuration & Settings in .NET Core Web API Let’s talk about one of the most underappreciated heroes of any backend system: Configuration Management.

When building real-world applications, flexibility is 🔑. You don’t want to hardcode values like connection strings, API keys, or feature flags — that’s where the configuration system in .NET Core comes in.


🧩 Where Configuration Comes From:

.NET Core supports multiple sources out of the box:

  • appsettings.json ✅
  • Environment variables 🌍
  • Command-line arguments 🧵
  • Secrets manager 🔐
  • Azure Key Vault ☁️ (for production-grade apps)


🗂️ Example of appsettings.json

This is example of configuration file for local development.

{
  "ConnectionStrings": {
    "Default": "Server=.;Database=MyDb;Trusted_Connection=True;"
  },
  "AppSettings": {
    "FeatureXEnabled": true,
    "MaxRetryCount": 3
  }
}        

🔧 Accessing Config via IConfiguration

public class MyService
{
    private readonly string _connString;

    public MyService(IConfiguration config)
    {
        _connString = config.GetConnectionString("Default");
    }
}        

Or for custom settings:

var featureEnabled = config.GetValue<bool>("AppSettings:FeatureXEnabled");        

🧪 Using IOptions for Strongly-Typed Settings

1. Define a class:

public class AppSettings
{
    public bool FeatureXEnabled { get; set; }
    public int MaxRetryCount { get; set; }
}        

2. Register and bind it in Program.cs:

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

3. Inject using IOptions<AppSettings>:

public class FeatureService
{
    private readonly AppSettings _settings;

    public FeatureService(IOptions<AppSettings> options)
    {
        _settings = options.Value;
    }
}        

🧠 What Makes .NET Core’s Configuration Powerful?

  • Environment Awareness Your app can behave differently in Development, Staging, and Production — without changing the code.
  • Centralized & Flexible All your configs live in one place but can be overridden using environment-specific settings.
  • Supports the 12-Factor App Methodology It cleanly separates config from code, making your app more maintainable, testable, and deployable.
  • Secure Secrets Management Easily integrate with Azure Key Vault, environment variables, or secret managers to protect sensitive data.
  • Injectable Settings Using IConfiguration and IOptions, config becomes part of your DI ecosystem, making it easy to use anywhere.


🛠 Real-World Scenarios

  • Switch DB connections based on environment ✅
  • Toggle features for different users or regions 🔄
  • Securely store 3rd-party API keys 🔐
  • Load settings from the cloud for distributed systems ☁️


📌 Pro Tip: Use dotnet user-secrets for local secret management in development!

To view or add a comment, sign in

Explore content categories