Configuration and Environments

7 min read

👋 Introduction

Welcome to the sixth module of the ASP.NET Core course. Thus far, we have built logic, handled requests, and returned responses. However, a robust application does not live in a vacuum. It requires configuration.

In the earliest days of computing, changing a database connection string or a listening port required recompiling the entire source code. This is, academically speaking, suboptimal. Today, we treat configuration as an external dependency, allowing our application to behave differently depending on the environment in which it runs—without changing a single line of C# code.

This guide will walk you through the modern configuration system in ASP.NET Core, moving from basic JSON files to secure secret management and strongly typed patterns.


1. appsettings.json: Storing Application Configuration 📄

Definition and Problem

The Problem: Hardcoding values inside your C# classes is a violation of the "Separation of Concerns" principle. If you hardcode a database connection string inside Program.cs, you must recompile and redeploy the application just to point it to a different server.

The Solution: ASP.NET Core uses a configuration provider system. The default and most common provider is the JSON file provider, specifically appsettings.json. This allows settings to be read at runtime.

Concept: The Configuration Builder

When an ASP.NET Core application starts, it builds a Key-Value pair collection from various sources. By default, the WebApplication.CreateBuilder(args) method loads configuration in this specific order:

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

Hands-on: Structure of appsettings.json

Open your project. You will see a file named appsettings.json. It is a standard JSON file.

json
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "MyAppSettings": {
    "ApplicationName": "CodeCampEats",
    "MaxItemsPerPage": 20,
    "Theme": "Dark"
  }
}

Accessing Configuration

To read these values, we typically inject IConfiguration into our components (though we will learn a better way in Subtopic 4).

Example in a Minimal API (Program.cs):

csharp
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/config", (IConfiguration config) =>
{
    // Accessing nested values using a colon (:) separator
    var appName = config["MyAppSettings:ApplicationName"];
    var theme = config["MyAppSettings:Theme"];
    
    return Results.Ok(new { AppName = appName, Theme = theme });
});

app.Run();

💡 Did You Know?
Before .NET Core, ASP.NET developers wrestled with a file called web.config. It was XML-based, extremely verbose, and often caused the "Yellow Screen of Death" if a single angle bracket was misplaced. The shift to JSON was celebrated globally, likely accompanied by fireworks in some developer communities.


2. Managing Secrets: Environment Variables and the Secret Manager 🔐

Definition and Problem

The Problem: You have an API Key for a payment gateway (e.g., Stripe) or a connection string with a real password. If you put this in appsettings.json and push your code to GitHub, bots scanning public repositories will steal your credentials within seconds. This happens daily in the industry.

The Solution: Never check secrets into source control. Instead, store them in Environment Variables or the Secret Manager tool during development.

Concept: The Secret Manager (User Secrets)

The Secret Manager tool stores sensitive data in a JSON file located in your local user profile directory (outside your project folder). This ensures it is physically impossible to commit it to Git.

Hands-on: Using Secret Manager

  1. Initialize User Secrets in your project directory:

    bash
    dotnet user-secrets init

    This adds a UserSecretsId to your project file (.csproj).

  2. Set a Secret:

    bash
    dotnet user-secrets set "PaymentSettings:ApiKey" "sk_test_12345_very_secret"
  3. Accessing it:
    ASP.NET Core automatically loads these secrets when the environment is set to "Development". You access them exactly the same way as appsettings.json:

    csharp
    var apiKey = config["PaymentSettings:ApiKey"];

Concept: Environment Variables

When you deploy to a server (Production), the Secret Manager is not used. Instead, we use Environment Variables. Most cloud providers (Azure, AWS, Docker) allow you to inject these.

Hierarchy Rule:
If appsettings.json has MaxItems: 10 but an Environment Variable exists named MaxItems with value 50, the Environment Variable wins. This allows you to override defaults without touching the file.

⚠️ Industry Standard:
For Linux/Docker environments, hierarchy is often represented by double underscores because colons are reserved.
MyAppSettings:ApplicationName becomes MyAppSettings__ApplicationName.


3. Context Matters: Working with Development vs. Production Environments 🌍

Definition and Problem

The Problem: In development, if your app crashes, you want a detailed error page showing the exact line of code that failed. In production, showing that same page reveals internal logic to hackers. Additionally, you might want to use a local database for dev and a cloud database for prod.

The Solution: ASP.NET Core uses an environment variable named ASPNETCORE_ENVIRONMENT to determine the current execution context.

Concept: IWebHostEnvironment

The framework provides the IWebHostEnvironment service to check the current environment.

Common values for ASPNETCORE_ENVIRONMENT:

  • Development
  • Staging
  • Production (Default if nothing is set)

Hands-on: Coding for Environments

In Program.cs, you will often see this pattern:

csharp
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    // Only runs when ASPNETCORE_ENVIRONMENT = Development
    app.UseDeveloperExceptionPage(); 
    app.UseSwagger();
    app.UseSwaggerUI();
    Console.WriteLine("🧪 We are in the lab (Dev Mode)");
}
else
{
    // Runs in Production/Staging
    app.UseExceptionHandler("/Error");
    app.UseHsts(); // Enforce strict security headers
    Console.WriteLine("🚀 We are live (Production Mode)");
}

app.Run();

Environment-Specific Configuration Files

Remember the file loading order?

  1. appsettings.json
  2. appsettings.Development.json

If you are in Development, values in the second file override the first. This allows you to keep appsettings.json for "Production defaults" and override them locally in appsettings.Development.json (which is usually safe to commit, provided it contains no secrets).

🧠 Imagination Exercise:
Think of the Development environment as a padded playground where it's okay to fall (throw exceptions) because the ground is soft (detailed logs).
Think of Production as a high-stakes surgical operation. It must be sterile, precise, and if something goes wrong, the patient (user) should only hear a polite "We are experiencing technical difficulties," not see the surgeon's internal notes.


4. The Options Pattern: Strongly Typed Settings for Clean Code 🧩

Definition and Problem

The Problem: Sprinkling config["Section:Key"] throughout your code is dangerous.

  1. Magic Strings: If you typo the key string, it returns null without throwing an error immediately.
  2. Coupling: Your business logic depends on IConfiguration, a massive object, when it only needs one or two settings.

The Solution: The Options Pattern. This technique binds a configuration section to a C# class (POCO - Plain Old CLR Object).

Step-by-Step Implementation

Step 1: Create the Settings Class

Create a class that mirrors the structure of your JSON section.

JSON:

json
"EmailSettings": {
  "SmtpServer": "smtp.example.com",
  "Port": 587,
  "SenderName": "Support Team"
}

C# Class:

csharp
public class EmailSettings
{
    public string SmtpServer { get; set; } = string.Empty;
    public int Port { get; set; }
    public string SenderName { get; set; } = string.Empty;
}

Step 2: Bind in Program.cs

Tell the Dependency Injection container to map the configuration section to your class.

csharp
var builder = WebApplication.CreateBuilder(args);

// This line binds the "EmailSettings" section of JSON to the EmailSettings class
builder.Services.Configure<EmailSettings>(
    builder.Configuration.GetSection("EmailSettings")
);

Step 3: Inject IOptions<T>

Now, instead of IConfiguration, you inject IOptions<EmailSettings> into your services or controllers.

csharp
app.MapGet("/send-email", (IOptions<EmailSettings> options) =>
{
    // We access the .Value property to get our class instance
    var settings = options.Value;
    
    return Results.Ok($"Sending email via {settings.SmtpServer} on port {settings.Port}");
});

Variations of Options

  • IOptions<T>: Singleton. Read once at startup. Best for settings that don't change.
  • IOptionsSnapshot<T>: Scoped. Re-read on every request. Useful if you change settings files while the app is running and want immediate updates.
  • IOptionsMonitor<T>: Singleton. capable of detecting changes and notifying subscribers.

🏛️ Academic Note:
The Options Pattern adheres to the Interface Segregation Principle and Single Responsibility Principle. Your service no longer cares about the entire configuration file; it only cares about the specific settings object it requires to function.


📚 Reference & Further Reading

For deep dives and official documentation, consult the following resources:

Challenge

You are tasked with setting up a strongly-typed configuration for an ASP.NET Core application using the Options Pattern. The application requires settings for a database connection and an external API, which are defined in appsettings.json.

Your goal is to correctly model, register, inject, and consume these settings.

  1. Define the C# properties within the provided DatabaseSettings and ApiSettings POCO classes. The property names must exactly match the keys in the corresponding JSON configuration sections shown in the initialCode comments.
  2. In Program.cs, register the DatabaseSettings and ApiSettings classes with the dependency injection container and bind them to the "Database" and "Api" configuration sections, respectively.
  3. Modify the DataProcessingService constructor to correctly inject the configuration options using the IOptions<T> interface.
  4. Implement the logic in the GetServiceConfigurationSummary method. It must access the injected options to retrieve the database connection string and the API key, returning a formatted string: "DB_Connect: [ConnectionString], API_Key: [ApiKey]".

Expected result

The final code should correctly implement the Options Pattern.

  1. The DatabaseSettings class must contain a public string property named ConnectionString.
  2. The ApiSettings class must contain two public string properties: Url and ApiKey.
  3. In the Program.cs section, there must be two calls to builder.Services.Configure<T>():
    • builder.Services.Configure<DatabaseSettings>(builder.Configuration.GetSection("Database"));
    • builder.Services.Configure<ApiSettings>(builder.Configuration.GetSection("Api"));
  4. The DataProcessingService constructor must accept IOptions<DatabaseSettings> and IOptions<ApiSettings> as parameters and assign them to private fields.
  5. The GetServiceConfigurationSummary method must access the .Value property on the injected options objects to construct and return the specified string, for example: return $"DB_Connect: {_dbSettings.Value.ConnectionString}, API_Key: {_apiSettings.Value.ApiKey}";.
csharp

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.