Student learning series · Lesson 5 of 6
Read appsettings.json with typed options, override configuration, and write structured logs.
What you will learn
Configuration keeps environment-specific values outside business logic. Options bind a configuration section to a class. Logging records useful events so you can understand application behavior.
1. Create the project
dotnet new web -n ConfigurationLesson
cd ConfigurationLessonReplace Program.cs and add the appsettings.json shown below in the project directory. Keep the server working directory at that project.
2. Complete Program.cs
using Microsoft.Extensions.Options;
var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<SchoolOptions>(
builder.Configuration.GetSection("School"));
var app = builder.Build();
app.MapGet("/school", (IOptions<SchoolOptions> options, ILogger<Program> logger) =>
{
logger.LogInformation("School information requested");
return Results.Ok(new { name = options.Value.Name });
});
app.Run();
class SchoolOptions
{
public string Name { get; set; } = "Learning Lab";
}
appsettings.json
{
"School": { "Name": "Student Learning Centre" }
}
3. Run and observe
dotnet run --no-launch-profile -- --urls http://127.0.0.1:5070Stop the server with Ctrl+C before starting the next lesson on the same port. For web lessons, visit the listed GET path at http://127.0.0.1:5070 in your browser. Use an HTTP client for POST, PUT and DELETE with Content-Type: application/json.
GET /school returns {"name":"Student Learning Centre"}.
The console records School information requested.4. Understand the code
Configure<SchoolOptions> registers the binding of the School section. IOptions<SchoolOptions> exposes its Value to the handler. With default configuration, environment variables can override JSON settings. School__Name maps to School:Name. ILogger is resolved by the container.
Practice exercise
In PowerShell set $env:School__Name = "Test Academy", restart the server, and request /school. Remove the variable afterward with Remove-Item Env:School__Name.
Self-check and answer
The returned name becomes Test Academy. The double underscore expresses a nested key. Do not put passwords or tokens in published appsettings files or log them. Use development user secrets or an appropriate secret store for real deployments.
Study notes
Type the example yourself, run it, change one behavior, and explain the result in your own words. Keep each lesson in its own project. These examples were compiled with .NET SDK 9.0.306; select a currently supported SDK for new study projects. The course teaches modern .NET and ASP.NET Core, rather than obsolete .NET Core 3.1 or classic Web Forms.
Return to the .NET Core student learning path · Official Microsoft documentation · .NET support policy
No comments:
Post a Comment
Please do not enter any spam link in the comment box.