The options pattern keeps related ASP.NET Core settings in a class and makes them available through dependency injection. It is commonly used to configure middleware. Define properties with defaults, then register changes with `builder.Services.Configure<TOptions>(...)` before calling `builder.Build()`. section 12.5
Listing 12.16 Using the options pattern in the Program.cs file in the Platform folder
using Microsoft.Extensions.Options;
using Platform;
var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<MessageOptions>(options => {
options.CityName = "Albany";
});
var app = builder.Build();
app.MapGet("/location", async (HttpContext context,
IOptions<MessageOptions> msgOpts) => {
Platform.MessageOptions opts = msgOpts.Value;
await context.Response.WriteAsync($"{opts.CityName}, "
+ opts.CountryName);
});
app.MapGet("/", () => "Hello World!");
app.Run();
A complete `Program.cs` example changes `MessageOptions.CityName` to `Albany`, then reads the registered options at `/location`. section 12.5
The `/location` handler receives `IOptions<MessageOptions>` as a parameter and reads its `Value`. With `CountryName` left at its default, the response is `Albany, USA`. Class-based middleware can instead receive `IOptions<MessageOptions>` in its constructor; `UseMiddleware<LocationMiddleware>()` resolves that parameter, and `Invoke` uses the settings while processing requests. section 12.5 section 12.5.1
Options can also come from configuration rather than a configuration callback. Pass `builder.Configuration.GetSection("Location")` to `Configure<MessageOptions>`; matching configuration keys replace property defaults. If `appsettings.json` sets only `Location:CityName` to `Buffalo`, `/location` uses `Buffalo` and retains the class’s default `CountryName`. section 15.2.4
The same approach configures other ASP.NET Core features:
- Set session idle time and cookie settings with `AddSession(opts => ...)`, then add `UseSession()` to the pipeline. A nonessential session cookie can cause trouble when cookie consent applies. section 16.3.1
- Add a Razor Page route with `Configure<RazorPagesOptions>` and `opts.Conventions.AddPageRoute(...)`; the added URL supplements the page’s existing route. section 23.3.2
- Change Identity’s login and access-denied redirect paths through named `CookieAuthenticationOptions` for the application scheme. section 39.3.5

