Skip to content
Explain to Dev
Explain to Dev

Empowering developers with the knowledge to build, create, and innovate in the software world.

  • Home
  • About
  • Java
  • Python
  • PHP
  • .NET
  • Node.js
  • SQL
  • Privacy Policy
Explain to Dev

Empowering developers with the knowledge to build, create, and innovate in the software world.

How to Use Configuration and Secrets in .NET Applications

etd_admin, September 13, 2025September 13, 2025

Modern .NET apps pull settings from many places—JSON files, environment variables, command-line args, Secret Manager, Azure Key Vault, and more. Knowing how to use configuration and secrets in .NET applications lets you keep code clean, secure, and flexible across environments (dev, test, prod).

Below is a practical, step-by-step guide with copy-pasteable snippets.

1) The Configuration System at a Glance

ASP.NET Core builds a unified configuration from multiple providers in this default order (later sources override earlier ones):

  1. appsettings.json
  2. appsettings.{Environment}.json (e.g., appsettings.Development.json)
  3. User Secrets (Development only)
  4. Environment variables
  5. Command-line arguments

You can add more providers (e.g., Azure Key Vault) as needed.

2) Start With appsettings.json

Create a base JSON file for non-sensitive defaults:

appsettings.json

{
  "App": {
    "Name": "TradeDesk",
    "PageSize": 50
  },
  "ConnectionStrings": {
    "MainDb": "Host=localhost;Database=tradedesk_dev;Username=app;Password=NOT_USED_IN_PROD"
  },
  "ExternalApi": {
    "BaseUrl": "https://api.example.com",
    "TimeoutSeconds": 15
  }
}

Environment-specific overrides go in, for example, appsettings.Development.json:

{
  "App": { "PageSize": 10 },
  "ExternalApi": { "TimeoutSeconds": 5 }
}

3) Read Settings via IConfiguration

Program.cs (Minimal API or ASP.NET Core)

var builder = WebApplication.CreateBuilder(args);

// IConfiguration is preconfigured with JSON, env vars, etc.
var configuration = builder.Configuration;

// Example: read simple values
string appName = configuration["App:Name"] ?? "MyApp";
int pageSize = configuration.GetValue<int>("App:PageSize");

// Example: read connection string
string mainDb = builder.Configuration.GetConnectionString("MainDb");

var app = builder.Build();

app.MapGet("/info", () => new { appName, pageSize, mainDbDefined = !string.IsNullOrEmpty(mainDb) });

app.Run();

4) Use the Options Pattern (Strongly Typed)

Create POCOs that mirror your JSON; bind and validate them once at startup.

Models/AppOptions.cs

public sealed class AppOptions
{
    public string Name { get; init; } = "MyApp";
    public int PageSize { get; init; } = 20;
}

Models/ExternalApiOptions.cs

public sealed class ExternalApiOptions
{
    public string BaseUrl { get; init; } = "";
    public int TimeoutSeconds { get; init; } = 10;
}

Program.cs

builder.Services.Configure<AppOptions>(builder.Configuration.GetSection("App"));
builder.Services.Configure<ExternalApiOptions>(builder.Configuration.GetSection("ExternalApi"));

var app = builder.Build();

app.MapGet("/typed", (Microsoft.Extensions.Options.IOptions<AppOptions> appOpts) =>
{
    var opts = appOpts.Value;
    return new { opts.Name, opts.PageSize };
});

app.Run();

Why this helps:

  • Centralized mapping & validation
  • Clean dependency injection
  • Easy unit testing

5) Keep Secrets Out of Source Control (User Secrets)

Never commit real passwords, API keys, or tokens. In Development, store them with the Secret Manager.

Initialize in your project directory:

dotnet user-secrets init

    Set secrets:

    dotnet user-secrets set "ConnectionStrings:MainDb" "Host=localhost;Database=prod;Username=app;Password=SuperSecret!"
    dotnet user-secrets set "ApiKeys:Stripe" "sk_live_..."

    These values are injected into configuration automatically only for ASPNETCORE_ENVIRONMENT=Development.

    Use them like normal:

    string secretDb = builder.Configuration.GetConnectionString("MainDb");
    string stripeKey = builder.Configuration["ApiKeys:Stripe"];

    This is the easiest way to use configuration and secrets in .NET applications during local development without risking leaks.

    6) Environment Variables for Containers & CI/CD

    In staging/prod (especially containers), environment variables are convenient and secure:

    Linux/macOS

    export ConnectionStrings__MainDb="Host=db;Database=app;Username=app;Password=${DB_PASSWORD}"
    export ExternalApi__BaseUrl="https://api.example.com"

    Windows (PowerShell)

    $env:ConnectionStrings__MainDb = "Host=db;Database=app;Username=app;Password=$env:DB_PASSWORD"
    $env:ExternalApi__BaseUrl = "https://api.example.com"

    Double underscores map to nested sections (e.g., ConnectionStrings:MainDb).

    When you use configuration and secrets in .NET applications correctly, you make your software safer and easier to operate across environments. Start with JSON + Options for clarity, use User Secrets locally, environment variables in CI/containers, and a managed secret store (like Azure Key Vault) for production. With these building blocks, you can confidently use configuration and secrets in .NET applications from development all the way to enterprise-grade deployments.

    .NET .NETEnvironment ConfigurationSecrets

    Post navigation

    Previous post
    Next post
    ©2025 Explain to Dev | WordPress Theme by SuperbThemes