Advertisement
Advanced ASP.NET Core, Configuration & Options Pattern

How do you write a custom IValidateOptions<T> implementation for validation logic beyond what DataAnnotations attributes can express?

Short answer

IValidateOptions .Validate(name, options) lets you implement arbitrary custom validation logic (like cross-field validation checking that one setting's value is consistent with another's, or an external check like verifying a configured URL is reachable) returning…

Save ASP.NET Core mock interview
Advertisement
AModel answer
IValidateOptions<T>.Validate(name, options) lets you implement arbitrary custom validation logic (like cross-field validation checking that one setting's value is consistent with another's, or an external check like verifying a configured URL is reachable) returning ValidateOptionsResult.Success or ValidateOptionsResult.Fail(errorMessage), registered via services.AddSingleton<IValidateOptions<T>, MyValidator>() and automatically invoked when combined with ValidateOnStart.
public class SmtpSettingsValidator : IValidateOptions<SmtpSettings> {
    public ValidateOptionsResult Validate(string? name, SmtpSettings options) {
        if (options.UseSsl && options.Port != 465 && options.Port != 587)
            return ValidateOptionsResult.Fail("SSL requires port 465 or 587");
        return ValidateOptionsResult.Success;
    }
}

builder.Services.AddSingleton<IValidateOptions<SmtpSettings>, SmtpSettingsValidator>();
Real-world example
A configuration validator catches an invalid combination (SSL enabled but using a non-SSL port) at application startup that simple per-field DataAnnotations attributes couldn't express, since it depends on the relationship between two separate settings.
Likely follow-ups
  • How does this combine with DataAnnotations validation running on the same options class?
  • What's the execution order if multiple IValidateOptions implementations exist for the same type?
Related topics