Md Mominul Islam | Software and Data Enginnering | SQL Server, .NET, Power BI, Azure Blog

while(!(succeed=try()));

LinkedIn Portfolio Banner

Latest

Home Top Ad

Responsive Ads Here

Post Top Ad

Responsive Ads Here

Tuesday, September 2, 2025

ASP.NET Core Configuration: How to Use appsettings.json and Environment Variables

 

Introduction: Why Configuration Matters in ASP.NET Core

Imagine you're developing an e-commerce platform for a retail startup. Your app needs to connect to a database, call external APIs, and adjust settings based on whether it's running locally, in staging, or production. Hard-coding these settings is a recipe for disaster—think connection string leaks or broken deployments. ASP.NET Core's configuration system, centered around appsettings.json and environment variables, solves this by providing a flexible, secure way to manage settings.

This beginner-to-advanced guide will teach you how to use appsettings.json and environment variables in ASP.NET Core. We'll build a realistic order management API, covering basic setups, environment-specific configs, and advanced scenarios like Azure Key Vault integration. With interactive "Try It Yourself" sections, code examples, pros/cons, alternatives, and best practices aligned with Microsoft and OWASP standards, you'll master configuration like a pro. Let’s dive in with Visual Studio or VS Code and ASP.NET Core 8.0!

Prerequisites

  • ASP.NET Core SDK (8.0 or later).
  • Visual Studio or VS Code.
  • Basic C# knowledge.
  • Optional: SQL Server or Azure account for advanced scenarios.

Topic 1: Understanding ASP.NET Core Configuration

What is Configuration in ASP.NET Core?

ASP.NET Core uses a configuration model that pulls settings from multiple sources (e.g., JSON files, environment variables, command-line args) into a unified IConfiguration interface. The primary sources are appsettings.json (for static settings) and environment variables (for dynamic or sensitive data).

Real-Life Scenario

In an e-commerce app, you need different database connections for development (local SQL Server) and production (Azure SQL). appsettings.json stores default settings, while environment variables override them in production for security.

Why Use appsettings.json and Environment Variables?

  • Flexibility: Switch settings per environment (Development, Staging, Production).
  • Security: Keep sensitive data (e.g., API keys) out of source control.
  • Maintainability: Centralize configuration for easy updates.

Pros and Cons

  • Pros: Built-in, flexible, supports multiple sources.
  • Cons: Misconfiguration can expose secrets; complex setups need careful management.
  • Alternatives: Third-party tools like HashiCorp Vault (Pros: Enterprise-grade security; Cons: Setup overhead).

Best Practices

  • Use appsettings.json for non-sensitive defaults.
  • Store sensitive data in environment variables or a secrets manager.
  • Standard: Follow OWASP A05:2021 for secure configuration.

Try It Yourself: Create a new ASP.NET Core Web API project (dotnet new webapi) and open appsettings.json. Notice the default JSON structure.

Topic 2: Basic Configuration with appsettings.json

Let’s set up a basic order management API with configuration stored in appsettings.json.

Step-by-Step

  1. Create appsettings.json: Define settings like API keys or connection strings.
  2. Access Configuration: Use IConfiguration in your app.
  3. Bind to Models: Map settings to strongly-typed classes for cleaner code.

Example Code: Basic appsettings.json Setup

csharp
// appsettings.json
{
"StoreSettings": {
"StoreName": "MyEcommerce",
"MaxOrderItems": 100
},
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=OrdersDb;User Id=sa;Password=StrongPass123;TrustServerCertificate=True;"
}
}
// StoreSettings.cs
public class StoreSettings
{
public string StoreName { get; set; }
public int MaxOrderItems { get; set; }
}
// Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
// Bind configuration to strongly-typed model
builder.Services.Configure<StoreSettings>(
builder.Configuration.GetSection("StoreSettings"));
var app = builder.Build();
app.UseAuthorization();
app.MapControllers();
app.Run();
// OrdersController.cs
[ApiController]
[Route("api/[controller]")]
public class OrdersController : ControllerBase
{
private readonly StoreSettings _settings;
public OrdersController(IOptions<StoreSettings> settings)
{
_settings = settings.Value;
}
[HttpGet("info")]
public IActionResult GetStoreInfo()
{
return Ok(new { _settings.StoreName, _settings.MaxOrderItems });
}
}

Explanation

  • appsettings.json: Stores static settings in JSON format.
  • IOptions<t></t>: Injects strongly-typed settings via DI.
  • GetSection: Retrieves a specific configuration section.

Real-Life Scenario

In a retail app, StoreSettings defined max order limits per environment, preventing developers from hard-coding values and easing updates.

Pros and Cons

  • Pros: Simple, built-in, supports JSON hierarchy.
  • Cons: Not ideal for sensitive data; requires manual reloading for changes.

Best Practices

  • Use IOptions<T> for strongly-typed access.
  • Keep appsettings.json in source control but exclude sensitive data.
  • Standard: Use JSON schema validation (Microsoft Docs).

Try It Yourself: Run the app (dotnet run), hit GET /api/orders/info, and verify the settings. Add a new setting (e.g., "Currency": "USD") and access it in the controller.

Topic 3: Using Environment Variables for Dynamic Configuration

Environment variables are perfect for sensitive data or environment-specific overrides (e.g., production database credentials).

Step-by-Step

  1. Set Environment Variables: Configure them in your OS, IDE, or hosting platform.
  2. Access in Code: Use IConfiguration to read variables.
  3. Override appsettings.json: Environment variables take precedence.

Example Code: Environment Variables

csharp
// appsettings.json (updated)
{
"StoreSettings": {
"StoreName": "MyEcommerce",
"MaxOrderItems": 100
},
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=OrdersDb;User Id=sa;Password=StrongPass123;TrustServerCertificate=True;"
}
}
// Program.cs (unchanged from above, as IConfiguration auto-loads env vars)
// OrdersController.cs (updated)
[ApiController]
[Route("api/[controller]")]
public class OrdersController : ControllerBase
{
private readonly IConfiguration _configuration;
private readonly StoreSettings _settings;
public OrdersController(IConfiguration configuration, IOptions<StoreSettings> settings)
{
_configuration = configuration;
_settings = settings.Value;
}
[HttpGet("info")]
public IActionResult GetStoreInfo()
{
// Read environment variable (e.g., override StoreName)
var storeName = _configuration["StoreSettings:StoreName"] ?? _settings.StoreName;
return Ok(new { StoreName = storeName, _settings.MaxOrderItems });
}
}

Setting Environment Variables

  • Windows: set StoreSettings__StoreName=ProdEcommerce
  • Linux/Mac: export StoreSettings__StoreName=ProdEcommerce
  • VS Code: Add to .vscode/launch.json under "env".
  • Note: Use double underscores (__) to map nested JSON keys.

Real-Life Scenario

In a deployed e-commerce app, environment variables overrode the database connection string in production, keeping credentials secure outside source control.

Pros and Cons

  • Pros: Secure for sensitive data; overrides appsettings.json easily.
  • Cons: Harder to manage locally; requires platform-specific setup.

Best Practices

  • Use : or __ for nested keys in environment variables.
  • Document variable names for team consistency.
  • Standard: OWASP secure configuration guidelines.

Try It Yourself: Set an environment variable (StoreSettings__StoreName=TestStore), restart the app, and hit the endpoint. Verify the override works.

Topic 4: Environment-Specific Configuration with appsettings.{Environment}.json

ASP.NET Core supports environment-specific files like appsettings.Development.json and appsettings.Production.json.

Step-by-Step

  1. Create Environment Files: Add appsettings.{Environment}.json files.
  2. Set Environment: Use ASPNETCORE_ENVIRONMENT variable.
  3. Access Settings: The framework automatically loads the right file.

Example Code: Environment-Specific Files

csharp
// appsettings.json
{
"StoreSettings": {
"StoreName": "MyEcommerce",
"MaxOrderItems": 100
}
}
// appsettings.Development.json
{
"StoreSettings": {
"StoreName": "DevEcommerce",
"MaxOrderItems": 50
}
}
// appsettings.Production.json
{
"StoreSettings": {
"StoreName": "ProdEcommerce",
"MaxOrderItems": 200
}
}
// Program.cs (updated to show environment)
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.Configure<StoreSettings>(
builder.Configuration.GetSection("StoreSettings"));
// Log environment for debugging
Console.WriteLine($"Environment: {builder.Environment.EnvironmentName}");
var app = builder.Build();
app.UseAuthorization();
app.MapControllers();
app.Run();

Setting the Environment

  • Local: Set ASPNETCORE_ENVIRONMENT=Development in Properties/launchSettings.json.
  • Production: Set via hosting platform (e.g., Azure App Service).
  • Verify: Check the console output for the environment name.

Real-Life Scenario

In a retail app, appsettings.Production.json set higher order limits for peak sales, while appsettings.Development.json used smaller limits for testing.

Pros and Cons

  • Pros: Clean separation of settings; no code changes needed.
  • Cons: Multiple files can lead to config drift if not managed.

Best Practices

  • Keep appsettings.json as the fallback.
  • Use environment-specific files for overrides only.
  • Standard: Microsoft configuration precedence rules.

Try It Yourself: Create appsettings.Development.json, set ASPNETCORE_ENVIRONMENT=Development, and test the endpoint. Switch to Production and observe changes.

Topic 5: Intermediate Configuration - Using User Secrets for Local Development

User Secrets store sensitive data outside appsettings.json during development, avoiding source control leaks.

Step-by-Step

  1. Initialize User Secrets: Run dotnet user-secrets init.
  2. Set Secrets: Add sensitive data via CLI.
  3. Access Secrets: Use IConfiguration as usual.

Example Code: User Secrets

csharp
// Initialize secrets
// Run in terminal: dotnet user-secrets init
// Set secret: dotnet user-secrets set "StoreSettings:ApiKey" "secret123"
// Program.cs (unchanged, as secrets are loaded automatically in Development)
// OrdersController.cs (updated)
[ApiController]
[Route("api/[controller]")]
public class OrdersController : ControllerBase
{
private readonly IConfiguration _configuration;
public OrdersController(IConfiguration configuration)
{
_configuration = configuration;
}
[HttpGet("api-key")]
public IActionResult GetApiKey()
{
var apiKey = _configuration["StoreSettings:ApiKey"];
return Ok(new { ApiKey = apiKey ?? "No API key set" });
}
}

Real-Life Scenario

In a team’s e-commerce project, User Secrets stored API keys locally, preventing accidental commits to GitHub.

Pros and Cons

  • Pros: Secure for local dev; integrates with IConfiguration.
  • Cons: Development-only; not suitable for production.

Best Practices

  • Use User Secrets for all sensitive local settings.
  • Clear secrets before sharing projects (dotnet user-secrets clear).
  • Standard: Microsoft User Secrets documentation.

Try It Yourself: Initialize User Secrets, set an API key, and test the endpoint. Check .csproj for the UserSecretsId and verify the secret isn’t in source control.

Topic 6: Advanced Configuration - Integrating Azure Key Vault

For production, Azure Key Vault securely stores sensitive data like connection strings and API keys.

Step-by-Step

  1. Set Up Azure Key Vault: Create a vault in Azure.
  2. Add Key Vault to ASP.NET Core: Install the NuGet package and configure.
  3. Access Secrets: Use IConfiguration to read from Key Vault.

Example Code: Azure Key Vault

csharp
// Install packages: dotnet add package Azure.Extensions.AspNetCore.Configuration.Secrets
// dotnet add package Azure.Identity
// Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
// Add Azure Key Vault
var keyVaultUrl = builder.Configuration["KeyVault:VaultUrl"];
builder.Configuration.AddAzureKeyVault(
new Uri(keyVaultUrl),
new DefaultAzureCredential());
var app = builder.Build();
app.UseAuthorization();
app.MapControllers();
app.Run();
// appsettings.json
{
"KeyVault": {
"VaultUrl": "https://myvault.vault.azure.net/"
}
}

Setup Notes

  • Create a Key Vault in Azure and add a secret (e.g., StoreSettings--ApiKey=prod123).
  • Grant your app access via Azure RBAC or access policies.
  • Use DefaultAzureCredential for local and production auth.

Real-Life Scenario

In a production e-commerce app, Key Vault stored database credentials, ensuring secure access and compliance with security audits.

Pros and Cons

  • Pros: Highly secure; integrates with Azure ecosystems.
  • Cons: Requires Azure setup; adds cost and complexity.

Best Practices

  • Use managed identities for Key Vault access.
  • Cache Key Vault secrets to reduce calls.
  • Standard: OWASP A05:2021 for secure storage.

Try It Yourself: Set up a free Azure account, create a Key Vault, add a secret, and test the endpoint. Verify the secret is loaded securely.

Topic 7: Best Practices, Standards, and Alternatives

Best Practices

  • Prioritize Security: Use environment variables or Key Vault for sensitive data.
  • Use Strongly-Typed Configs: Prefer IOptions<T> for clarity.
  • Validate Configs: Check for missing settings at startup.
  • Monitor Changes: Use IOptionsSnapshot<T> for reloadable settings.

Standards

  • Microsoft configuration guidelines for source precedence.
  • OWASP A05:2021 for secure configuration management.

Alternatives

  • HashiCorp Vault: Enterprise-grade secret management (Pros: Cross-platform; Cons: Complex setup).
  • Configuration Files Only: Simple but less secure for sensitive data.

Pros and Cons of ASP.NET Core Configuration

  • Pros: Flexible, built-in, supports multiple sources.
  • Cons: Requires careful management to avoid leaks or misconfigurations.

Conclusion: Take Control of Your ASP.NET Core Configuration

From appsettings.json to Azure Key Vault, you’ve learned how to configure ASP.NET Core apps like a pro. These skills will make your apps secure, scalable, and maintainable. Experiment with the examples, try different environments, and share your configuration stories in the comments. What’s your next config challenge?

No comments:

Post a Comment

Thanks for your valuable comment...........
Md. Mominul Islam

Post Bottom Ad

Responsive Ads Here