Options Pattern in ASP.NET Core: Bind, Validate and Reload appsettings.json (.NET 10)

One wrong letter in a config key is the bug I see most in ASP.NET Core apps. This compiles, runs without a warning, and quietly gives every customer free shipping:

#:sdk Microsoft.NET.Sdk.Web
#:property PublishAot=false
var builder = WebApplication.CreateBuilder(args);

// typo: "Shiping" - no error, just a default value
var threshold = builder.Configuration.GetValue<decimal>("Shipping:FreeShipingThreshold");
Console.WriteLine($"Free shipping on orders over ${threshold}");
Free shipping on orders over $0

A threshold of $0 means every order ships free. The fix is the options pattern ASP.NET Core ships with: bind the JSON section to a typed class once, validate it at startup, and inject IOptions<T> where you need it.

Here’s what we’re building, a .NET 10 shipping-quote API whose settings all come from appsettings.json:

Options pattern in ASP.NET Core: VS Code shows appsettings.json with the Shipping and Carriers sections, and dotnet run ShippingApi.cs prints three shipping quotes built from those values
The finished ShippingApi: appsettings.json on top, the quotes it produces in the terminal

What Is the Options Pattern in ASP.NET Core?

The options pattern binds a configuration section, such as Shipping in appsettings.json, to a plain C# class and registers it with ASP.NET Core dependency injection. Code asks for the class instead of reading string keys.

You get checked property names, one place to validate, and three wrappers that decide whether a running app sees file edits:

InterfaceLifetimeSees file changes?Named optionsUse it in
IOptions<T>SingletonNo, read onceNoSettings that never change at runtime
IOptionsSnapshot<T>ScopedYes, per requestYesEndpoints, controllers, scoped services
IOptionsMonitor<T>SingletonYes, any time + OnChangeYesSingletons and background services

The options class must be a non-abstract class with a public parameterless constructor and public read-write properties. Fields aren’t bound.

Before You Start the Options Pattern Build

You need the .NET 10 SDK (I used 10.0.402); check your installed .NET version if you’re not sure. No NuGet packages are needed, because everything used here ships in the ASP.NET Core shared framework.

Every demo is a single-file app from what’s new in .NET 10: #:sdk Microsoft.NET.Sdk.Web makes it a web app. I added #:property PublishAot=false because file-based apps default to Native AOT, which warns about reflection-based validation.

The store ships from Austin, Texas. Create a folder with this appsettings.json:

{
  "Shipping": {
    "FreeShippingThreshold": 75.00,
    "FlatRate": 8.95,
    "WarehouseZip": "78701",
    "DefaultCarrier": "USPS"
  },
  "Carriers": {
    "UPS": { "MaxWeightLbs": 150, "PickupCutoff": "5:00 PM" },
    "USPS": { "MaxWeightLbs": 70, "PickupCutoff": "3:30 PM" }
  }
}
KeyTypeValueMeaning
Shipping:FreeShippingThresholddecimal75.00Orders at or above this ship free (USD)
Shipping:FlatRatedecimal8.95Fee below the threshold
Shipping:WarehouseZipstring78701Austin, TX warehouse
Shipping:DefaultCarrierstringUSPSCarrier for light boxes
Carriers:UPS / Carriers:USPSobject150 / 70 lbsPer-carrier limits (named options)

Step 1: Create the ShippingOptions Class and Bind appsettings.json

Make a class whose property names match the JSON keys, then bind the section with Get<T>() to prove the names line up.

  1. Add a ShippingOptions class with one property per key under Shipping.
  2. Give it a Section constant so the string "Shipping" lives in one place (constants aren’t bound).
  3. Call GetSection(...).Get<ShippingOptions>() and print each value.
#:sdk Microsoft.NET.Sdk.Web
#:property PublishAot=false
var builder = WebApplication.CreateBuilder(args);

var shipping = builder.Configuration
    .GetSection(ShippingOptions.Section)
    .Get<ShippingOptions>()!;

Console.WriteLine($"Free shipping over: ${shipping.FreeShippingThreshold}");
Console.WriteLine($"Flat rate:          ${shipping.FlatRate}");
Console.WriteLine($"Warehouse ZIP:      {shipping.WarehouseZip}");
Console.WriteLine($"Default carrier:    {shipping.DefaultCarrier}");

public class ShippingOptions
{
    public const string Section = "Shipping";
    public decimal FreeShippingThreshold { get; set; }
    public decimal FlatRate { get; set; }
    public string WarehouseZip { get; set; } = "";
    public string DefaultCarrier { get; set; } = "";
}

Output:

Free shipping over: $75.00
Flat rate:          $8.95
Warehouse ZIP:      78701
Default carrier:    USPS
Options pattern ASP.NET Core step 1 in VS Code: BindShipping.cs binds the Shipping section of appsettings.json to the ShippingOptions class and the terminal prints $75.00, $8.95, 78701 and USPS
Every JSON value landed on the matching ShippingOptions property

Checkpoint: four lines with $75.00, $8.95, 78701 and USPS. A zero or blank value means a property name doesn’t match its key.

The ! after Get is the null-forgiving operator from nullable reference types in C#: Get returns null when the section is missing. Binding also ignores case and never throws on a missing key.

Step 2: Register the Options with builder.Services.Configure and Inject IOptions

Registering the class lets any endpoint, controller or service ask for it instead of binding by hand.

  1. Call builder.Services.Configure<ShippingOptions>(section) before builder.Build().
  2. Add IOptions<ShippingOptions> options as an endpoint parameter (or constructor parameter).
  3. Read the bound object from options.Value.
#:sdk Microsoft.NET.Sdk.Web
#:property PublishAot=false
using Microsoft.Extensions.Options;

var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Services.Configure<ShippingOptions>(
    builder.Configuration.GetSection(ShippingOptions.Section));
var app = builder.Build();

app.MapGet("/quote", (decimal subtotal, IOptions<ShippingOptions> options) =>
{
    ShippingOptions o = options.Value;
    decimal fee = subtotal >= o.FreeShippingThreshold ? 0.00m : o.FlatRate;
    return $"Subtotal ${subtotal} -> shipping ${fee} via {o.DefaultCarrier}";
});

app.Urls.Add("http://localhost:5878");
await app.StartAsync();
var http = new HttpClient { BaseAddress = new Uri("http://localhost:5878") };
Console.WriteLine(await http.GetStringAsync("/quote?subtotal=42.50"));
Console.WriteLine(await http.GetStringAsync("/quote?subtotal=75.00"));
await app.StopAsync();

public class ShippingOptions
{
    public const string Section = "Shipping";
    public decimal FreeShippingThreshold { get; set; }
    public decimal FlatRate { get; set; }
    public string WarehouseZip { get; set; } = "";
    public string DefaultCarrier { get; set; } = "";
}

Output:

Subtotal $42.50 -> shipping $8.95 via USPS
Subtotal $75.00 -> shipping $0.00 via USPS
ASP.NET Core options pattern step 2 in VS Code: builder.Services.Configure<ShippingOptions> plus an IOptions<ShippingOptions> parameter in a minimal API endpoint, with quotes for $42.50 and $75.00 subtotals
The /quote endpoint reads the threshold and flat rate from IOptions

Checkpoint: Subtotal $42.50 -> shipping $8.95 via USPS and then Subtotal $75.00 -> shipping $0.00 via USPS.

The same parameter works in controllers too; the minimal API vs controllers comparison shows both styles side by side.

Step 3: Use AddOptions().Bind with ValidateDataAnnotations and ValidateOnStart

Configure accepts anything, including a negative threshold. AddOptions<T>() returns an OptionsBuilder that chains binding and validation.

  1. Replace Configure with AddOptions<ShippingOptions>().BindConfiguration(ShippingOptions.Section).
  2. Add [Range], [Required] and [RegularExpression] attributes, then call ValidateDataAnnotations().
  3. Add a cross-property rule with Validate(o => ..., "message").
  4. End with ValidateOnStart() so bad settings stop the app at startup.
#:sdk Microsoft.NET.Sdk.Web
#:property PublishAot=false
using System.ComponentModel.DataAnnotations;
using Microsoft.Extensions.Options;

var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Services.AddOptions<ShippingOptions>()
    .BindConfiguration(ShippingOptions.Section)
    .ValidateDataAnnotations()
    .Validate(o => o.FlatRate < o.FreeShippingThreshold,
        "FlatRate must be lower than FreeShippingThreshold.")
    .ValidateOnStart();
var app = builder.Build();

app.Urls.Add("http://localhost:5878");
try
{
    await app.StartAsync();   // ValidateOnStart runs here, before any request
}
catch (OptionsValidationException ex)
{
    foreach (string failure in ex.Failures)
        Console.WriteLine($"Invalid setting: {failure}");
    return;
}
var o = app.Services.GetRequiredService<IOptions<ShippingOptions>>().Value;
Console.WriteLine($"Started: free over ${o.FreeShippingThreshold}, ZIP {o.WarehouseZip}");
await app.StopAsync();

public class ShippingOptions
{
    public const string Section = "Shipping";
    [Range(0.01, 500)] public decimal FreeShippingThreshold { get; set; }
    [Range(0, 50)] public decimal FlatRate { get; set; }
    [Required, RegularExpression(@"^\d{5}$")] public string WarehouseZip { get; set; } = "";
    [Required] public string DefaultCarrier { get; set; } = "";
}

Output:

Started: free over $75.00, ZIP 78701

StartAsync throws OptionsValidationException, and its Failures list holds one message per broken rule. I print them instead of letting a stack trace bury them.

To test the rules, I broke two values with environment variables (Step 6 explains why they beat the JSON):

set "Shipping__FreeShippingThreshold=-5" && set "Shipping__WarehouseZip=7870" && dotnet run ValidateShipping.cs
Invalid setting: DataAnnotation validation failed for 'ShippingOptions' members: 'FreeShippingThreshold' with the error: 'The field FreeShippingThreshold must be between 0.01 and 500.'.
Invalid setting: DataAnnotation validation failed for 'ShippingOptions' members: 'WarehouseZip' with the error: 'The field WarehouseZip must match the regular expression '^\d{5}$'.'.
Invalid setting: FlatRate must be lower than FreeShippingThreshold.
ValidateDataAnnotations and ValidateOnStart in ASP.NET Core: ValidateShipping.cs catches the OptionsValidationException thrown by StartAsync and prints the FreeShippingThreshold range, WarehouseZip pattern and FlatRate rule failures
ValidateOnStart stops the app before it serves a single request

Checkpoint: the good run prints Started: free over $75.00, ZIP 78701, and the broken run prints three Invalid setting lines, including the FlatRate rule.

Without ValidateOnStart, the same exception waits for the first .Value read, usually inside a customer’s request. Pair it with global error handling in ASP.NET Core for errors that do slip through.

Step 4: Compare IOptions vs IOptionsSnapshot vs IOptionsMonitor with a Live Reload

WebApplication.CreateBuilder loads appsettings.json with reload-on-change turned on. Whether your code notices depends on the interface you inject.

  1. Inject all three interfaces into one /threshold endpoint.
  2. Register an OnChange callback on IOptionsMonitor.
  3. While the app runs, rewrite the threshold in appsettings.json from 75.00 to 50.00, then put it back.
#:sdk Microsoft.NET.Sdk.Web
#:property PublishAot=false
using Microsoft.Extensions.Options;

var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Services.Configure<ShippingOptions>(builder.Configuration.GetSection("Shipping"));
var app = builder.Build();

app.MapGet("/threshold", (IOptions<ShippingOptions> options,
    IOptionsSnapshot<ShippingOptions> snapshot, IOptionsMonitor<ShippingOptions> monitor) =>
    $"IOptions ${options.Value.FreeShippingThreshold} | " +
    $"IOptionsSnapshot ${snapshot.Value.FreeShippingThreshold} | " +
    $"IOptionsMonitor ${monitor.CurrentValue.FreeShippingThreshold}");

app.Services.GetRequiredService<IOptionsMonitor<ShippingOptions>>()
    .OnChange(o => Console.WriteLine($"OnChange: threshold is now ${o.FreeShippingThreshold}"));

app.Urls.Add("http://localhost:5878");
await app.StartAsync();
var http = new HttpClient { BaseAddress = new Uri("http://localhost:5878") };
Console.WriteLine("Before: " + await http.GetStringAsync("/threshold"));

string original = File.ReadAllText("appsettings.json");
File.WriteAllText("appsettings.json", original.Replace("75.00", "50.00"));  // edit while running
await Task.Delay(1500);
Console.WriteLine("After:  " + await http.GetStringAsync("/threshold"));

File.WriteAllText("appsettings.json", original);  // put the file back
await Task.Delay(1500);
await app.StopAsync();

public class ShippingOptions
{
    public const string Section = "Shipping";
    public decimal FreeShippingThreshold { get; set; }
    public decimal FlatRate { get; set; }
    public string WarehouseZip { get; set; } = "";
    public string DefaultCarrier { get; set; } = "";
}

Output:

Before: IOptions $75.00 | IOptionsSnapshot $75.00 | IOptionsMonitor $75.00
OnChange: threshold is now $50.00
OnChange: threshold is now $50.00
After:  IOptions $75.00 | IOptionsSnapshot $50.00 | IOptionsMonitor $50.00
OnChange: threshold is now $75.00
OnChange: threshold is now $75.00
IOptions vs IOptionsSnapshot vs IOptionsMonitor in ASP.NET Core: after appsettings.json changes from 75.00 to 50.00 while the app runs, IOptions still returns $75.00 while IOptionsSnapshot and IOptionsMonitor return $50.00
Only IOptions keeps the startup value after the file changes

Checkpoint: the After line reads IOptions $75.00 | IOptionsSnapshot $50.00 | IOptionsMonitor $50.00.

IOptions caches its value for the life of the app. IOptionsSnapshot rebinds once per request, and IOptionsMonitor.CurrentValue always has the latest values. The Task.Delay calls just give the file watcher time; see async and await in C# for how those awaits work.

Note: the OnChange line can print more than once for a single save, because the file watcher may raise several events. Make OnChange handlers safe to run twice.

Step 5: Add Named Options for Each Carrier

UPS and USPS share one shape but have different limits. Named options register the same CarrierOptions class twice under different names.

  1. Call Configure<CarrierOptions>("UPS", section) once per carrier.
  2. Inject IOptionsSnapshot<CarrierOptions> or IOptionsMonitor<CarrierOptions>; plain IOptions has no named support.
  3. Read one with Get("UPS").
#:sdk Microsoft.NET.Sdk.Web
#:property PublishAot=false
using Microsoft.Extensions.Options;

var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Services.Configure<CarrierOptions>("UPS", builder.Configuration.GetSection("Carriers:UPS"));
builder.Services.Configure<CarrierOptions>("USPS", builder.Configuration.GetSection("Carriers:USPS"));
var app = builder.Build();

app.MapGet("/carriers/{name}", (string name, IOptionsSnapshot<CarrierOptions> carriers) =>
{
    CarrierOptions c = carriers.Get(name);
    return $"{name,-5} max {c.MaxWeightLbs,3} lbs, pickup cutoff '{c.PickupCutoff}'";
});

app.Urls.Add("http://localhost:5878");
await app.StartAsync();
var http = new HttpClient { BaseAddress = new Uri("http://localhost:5878") };
foreach (var name in new[] { "UPS", "USPS", "FedEx" })
    Console.WriteLine(await http.GetStringAsync($"/carriers/{name}"));
await app.StopAsync();

public class CarrierOptions
{
    public int MaxWeightLbs { get; set; }
    public string PickupCutoff { get; set; } = "";
}

Output:

UPS   max 150 lbs, pickup cutoff '5:00 PM'
USPS  max  70 lbs, pickup cutoff '3:30 PM'
FedEx max   0 lbs, pickup cutoff ''
Named options in ASP.NET Core: NamedCarriers.cs registers CarrierOptions for UPS and USPS and IOptionsSnapshot.Get returns 150 lbs and 70 lbs, while the unknown FedEx name returns 0 lbs and an empty cutoff
Get(“FedEx”) doesn’t throw; it hands back an empty CarrierOptions

Checkpoint: UPS shows 150 lbs, USPS shows 70 lbs, and FedEx shows 0 with a blank cutoff.

That FedEx line is the trap: an unknown name returns a default instance, not an error. Validate named options with AddOptions<T>("UPS") if a missing carrier should fail.

Step 6: Override Options with appsettings.Development.json and Environment Variables

Configuration sources stack, and the last one wins. For a default web app the order is appsettings.json, then appsettings.{Environment}.json, then environment variables, then command-line arguments.

  1. Add appsettings.Development.json with only the keys that differ on a dev box.
  2. Set ASPNETCORE_ENVIRONMENT=Development to load it.
  3. Set Shipping__FlatRate to override one key; the double underscore stands for the colon.
{
  "Shipping": {
    "FreeShippingThreshold": 25.00,
    "WarehouseZip": "78758"
  }
}
#:sdk Microsoft.NET.Sdk.Web
#:property PublishAot=false
using Microsoft.Extensions.Options;

var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<ShippingOptions>(builder.Configuration.GetSection("Shipping"));
var app = builder.Build();

var o = app.Services.GetRequiredService<IOptions<ShippingOptions>>().Value;
Console.WriteLine($"{app.Environment.EnvironmentName,-11}: free over ${o.FreeShippingThreshold}, " +
    $"flat ${o.FlatRate}, ZIP {o.WarehouseZip}");

public class ShippingOptions
{
    public const string Section = "Shipping";
    public decimal FreeShippingThreshold { get; set; }
    public decimal FlatRate { get; set; }
    public string WarehouseZip { get; set; } = "";
    public string DefaultCarrier { get; set; } = "";
}

Output:

Production : free over $75.00, flat $8.95, ZIP 78701
Development: free over $25.00, flat $8.95, ZIP 78758
Development: free over $25.00, flat $5.95, ZIP 78758
Options pattern environment override in ASP.NET Core: three runs of EnvOverride.cs show Production values from appsettings.json, Development values from appsettings.Development.json, and a FlatRate of 5.95 from an environment variable
Same code, three runs: the JSON file, the Development file, then an environment variable

Checkpoint: the last line reads Development: free over $25.00, flat $5.95, ZIP 78758.

Keys you don’t override keep their appsettings.json values, so the Development file stays tiny. Connection strings work the same way, as in this ASP.NET Core Web API CRUD with EF Core build.

Test the ShippingApi with IOptionsMonitor in a Singleton Service

The finished app puts it together: validated ShippingOptions, named carriers, and a ShippingCalculator singleton that reads both through IOptionsMonitor.

#:sdk Microsoft.NET.Sdk.Web
#:property PublishAot=false
using System.ComponentModel.DataAnnotations;
using Microsoft.Extensions.Options;

var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Services.AddOptions<ShippingOptions>()
    .BindConfiguration(ShippingOptions.Section)
    .ValidateDataAnnotations()
    .ValidateOnStart();
builder.Services.Configure<CarrierOptions>("UPS", builder.Configuration.GetSection("Carriers:UPS"));
builder.Services.Configure<CarrierOptions>("USPS", builder.Configuration.GetSection("Carriers:USPS"));
builder.Services.AddSingleton<ShippingCalculator>();
var app = builder.Build();

app.MapGet("/quote", (decimal subtotal, double weightLbs, ShippingCalculator calc) =>
    calc.Quote(subtotal, weightLbs));

app.Urls.Add("http://localhost:5878");
await app.StartAsync();
var http = new HttpClient { BaseAddress = new Uri("http://localhost:5878") };
Console.WriteLine($"ShippingApi ({app.Environment.EnvironmentName})");
Console.WriteLine(await http.GetStringAsync("/quote?subtotal=42.50&weightLbs=3"));
Console.WriteLine(await http.GetStringAsync("/quote?subtotal=89.99&weightLbs=12.5"));
Console.WriteLine(await http.GetStringAsync("/quote?subtotal=64.00&weightLbs=95"));
await app.StopAsync();

// singleton service: IOptionsMonitor is safe here, IOptionsSnapshot (scoped) is not
public class ShippingCalculator(IOptionsMonitor<ShippingOptions> shipping,
    IOptionsMonitor<CarrierOptions> carriers)
{
    public string Quote(decimal subtotal, double weightLbs)
    {
        ShippingOptions s = shipping.CurrentValue;
        string carrier = weightLbs > carriers.Get("USPS").MaxWeightLbs ? "UPS" : s.DefaultCarrier;
        decimal fee = subtotal >= s.FreeShippingThreshold ? 0.00m : s.FlatRate;
        return $"${subtotal}, {weightLbs} lbs -> ${fee} via {carrier}, " +
               $"pickup by {carriers.Get(carrier).PickupCutoff}";
    }
}

public class ShippingOptions
{
    public const string Section = "Shipping";
    [Range(0.01, 500)] public decimal FreeShippingThreshold { get; set; }
    [Range(0, 50)] public decimal FlatRate { get; set; }
    [Required, RegularExpression(@"^\d{5}$")] public string WarehouseZip { get; set; } = "";
    [Required] public string DefaultCarrier { get; set; } = "";
}

public class CarrierOptions
{
    public int MaxWeightLbs { get; set; }
    public string PickupCutoff { get; set; } = "";
}

Output:

ShippingApi (Production)
$42.50, 3 lbs -> $8.95 via USPS, pickup by 3:30 PM
$89.99, 12.5 lbs -> $0.00 via USPS, pickup by 3:30 PM
$64.00, 95 lbs -> $8.95 via UPS, pickup by 5:00 PM

In Production, a $42.50 order pays the flat rate, $89.99 ships free, and a 95 lb box goes UPS because it’s over the USPS 70 lb limit. That’s the run in the first screenshot.

Running it with the Development environment drops the free-shipping line to $25.00:

ShippingApi (Development)
$42.50, 3 lbs -> $0.00 via USPS, pickup by 3:30 PM
$89.99, 12.5 lbs -> $0.00 via USPS, pickup by 3:30 PM
$64.00, 95 lbs -> $0.00 via UPS, pickup by 5:00 PM
Options pattern ASP.NET Core test: ShippingApi.cs with a ShippingCalculator singleton using IOptionsMonitor, run with ASPNETCORE_ENVIRONMENT=Development so the $64.00 order ships free
Development settings make every order over $25.00 ship free

Important: the calculator is a singleton, so it can’t take the scoped IOptionsSnapshot; IOptionsMonitor fits. To grow this into a full project, run dotnet project convert ShippingApi.cs, covered in file-based apps with dotnet run.

Troubleshooting the Options Pattern in ASP.NET Core

Values are 0 or empty. A property name doesn’t match its key, the section name is wrong, or the setter isn’t public. Print the bound object like Step 1 does.

Cannot consume scoped service IOptionsSnapshot from singleton. Use IOptionsMonitor in singletons and hosted services.

OptionsValidationException on the first request. Add ValidateOnStart() so it fails at deploy time instead, and log the message in a try-catch block if you read options outside DI.

Where to Take It Next with ASP.NET Core Options

Move validation rules into a class that implements IValidateOptions<T>, or use the [OptionsValidator] source generator for trim-friendly validation. Then wire the same pattern into your custom ASP.NET Core middleware settings.

For API keys and connection strings, bind a settings class the same way in JWT authentication in ASP.NET Core. Keep the real secret values out of appsettings.json.

Other reading I’d line up after this build:

Frequently Asked Questions

What is the options pattern in ASP.NET Core?

It binds a configuration section to a typed class and registers it in dependency injection, so code reads IOptions<T> instead of string keys like "Shipping:FlatRate".

What’s the difference between IOptions, IOptionsSnapshot and IOptionsMonitor?

IOptions is a singleton that reads values once. IOptionsSnapshot is scoped and rebinds per request. IOptionsMonitor is a singleton with CurrentValue, named options and OnChange notifications.

Should I use Configure or AddOptions?

Both register the same options. AddOptions<T>() returns an OptionsBuilder, so use it when you want Bind, ValidateDataAnnotations and ValidateOnStart in one chain.

Does IOptions reload when appsettings.json changes?

No. In my run it kept $75.00 after the file changed to $50.00, while IOptionsSnapshot and IOptionsMonitor returned $50.00. See the Options pattern in ASP.NET Core guide on Microsoft Learn.

When does options validation run?

The first time the options object is created, unless you call ValidateOnStart(). Then it runs during app startup and the app won’t start with bad values. It also runs again on every reload.