DEV Community

Anton Martyniuk
Anton Martyniuk

Posted on Originally published at antondevtips.com

How to Validate Configuration in ASP.NET Core

Your app starts fine.
The first few requests work.
Then, hours later, one feature reaches for a setting that was never configured - and throws, deep in a request, far from the real cause.

I've been through this multiple times.

Configuration is just JSON or strings until you validate it.

ASP.NET Core can check your configuration the moment the app starts, so a typo in appsettings.json stops the app right away instead of returning a 500 Internal Error later.

There are two ways to do this: Data Annotations and FluentValidation.

In this post, we will explore:

  • Why configuration validation matters
  • Validate with Data Annotations
  • Fail fast at startup with ValidateOnStart
  • Validate with FluentValidation
  • Cross-field rules and named options
  • Data Annotations vs FluentValidation: when to use each

Let's dive in.

Why Configuration Validation Matters

Most apps bind configuration to a strongly typed class with the Options pattern.

Here is a settings class for talking to the GitHub API:

public sealed class GitHubSettings
{
    public string Token { get; set; } = string.Empty;
    public string BaseUrl { get; set; } = string.Empty;
    public int RetryCount { get; set; }
    public int RetryDelaySeconds { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

It is bound from appsettings.json:

{
  "GitHubSettings": {
    "Token": "ghp_xxx",
    "BaseUrl": "https://api.github.com",
    "RetryCount": 3,
    "RetryDelaySeconds": 2
  }
}
Enter fullscreen mode Exit fullscreen mode
builder.Services
    .AddOptions<GitHubSettings>()
    .Bind(builder.Configuration.GetSection(nameof(GitHubSettings)));
Enter fullscreen mode Exit fullscreen mode

This binds the section, but it does not check anything.

If Token is missing or RetryCount is 0, binding still succeeds - you get an empty string and a zero.
The problem only shows up later, when some code actually uses those values.

An empty Token sails through binding and only fails when you make your first GitHub call - as a 401, or a NullReferenceException three layers deep, with nothing pointing back to the real cause: a missing config value.

Validation closes that gap. It turns a silent, half-configured object into an immediate failure.

If the Options pattern is new to you, start with Master Configuration in ASP.NET Core with the Options Pattern.


👉 Read the full article on my newsletter: https://antondevtips.com/blog/how-to-validate-configuration-in-aspnet-core

Top comments (0)