Configuration
What this covers
Section titled “What this covers”Configuration comes from layered providers: appsettings.json, then appsettings.{Environment}.json, then user secrets, environment variables and the command line, with later layers winning. This page covers reading values through IConfiguration, binding sections to typed classes with the options pattern, and validating options at startup.
A taste of the options pattern:
using Microsoft.Extensions.Options;
var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<GreetingOptions>( builder.Configuration.GetSection(GreetingOptions.SectionName));
var app = builder.Build();
app.MapGet("/greeting", (IOptions<GreetingOptions> options) => options.Value.Message);
app.Run();
public sealed class GreetingOptions{ public const string SectionName = "Greeting"; public string Message { get; set; } = "";}Exercise 01: bind configuration to options
Section titled “Exercise 01: bind configuration to options”Goal: serve a greeting whose text comes from configuration, so it can be changed per environment without touching code.
Where: samples/exercises/01-configuration in the GitHub repo. Clone the repo, then work in the Starter project.
Steps:
- Open
Starter/Program.csand find theTODOcomments. - Bind the
Greetingsection of configuration toGreetingOptions. - Make
GET /greetingreturnGreetingOptions.Messageinstead of501 Not Implemented. - Check that an environment variable (
Greeting__Message) overrides the value inappsettings.json.
Check your work: the tests start red and turn green as you go.
dotnet test --project samples/exercises/01-configuration/Starter.TestsStuck? Compare with the Solution project next to it. The exercises are for practice only, and nothing is recorded or submitted.