Home > Net >  How to validate configuration based on Data Annotations?
How to validate configuration based on Data Annotations?

Time:11-10

How do I validate this configuration based on the Data Annotations I put?

var dbConfiguration = builder.Configuration.GetSection("AWS:DynamoDB").Get<DynamoDbConfiguration>();

public class DynamoDbConfiguration
{
    [Required]
    public required string AccessKey { get; init; }

    [Required]
    public required string SecretKey { get; init; }

    [Required]
    [RegularExpression(@"[(http(s)?):\/\/(www\.)?a-zA-Z0-9@:%._\ ~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\ .~#?&//=]*)")]
    public required string ServiceUrl { get; init; }

    [Required]
    [RegularExpression(@"(us(-gov)?|ap|ca|cn|eu|sa)-(central|(north|south)?(east|west)?)-\d ")]
    public required string Region { get; init; }
}

CodePudding user response:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOptions<DynamoDbConfiguration>()
    .Bind(builder.Configuration.GetSection("AWS:DynamoDB"))
    .ValidateDataAnnotations()
    .ValidateOnStart();

var myApp = builder.Build();
myApp.Run();

Output:

Unhandled exception. Microsoft.Extensions.Options.OptionsValidationException: DataAnnotation validation failed for 'DynamoDbConfiguration' members: 'AccessKey' with the error: 'The AccessKey field is required.'.; DataAnnotation validation failed for 'DynamoDbConfiguration' members: 'SecretKey' with the error: 'The SecretKey field is required.'.; DataAnnotation validation failed for 'DynamoDbConfiguration' members: 'ServiceUrl' with the error: 'The field ServiceUrl must match the regular expression '[(http(s)?):\/\/(www\.)?a-zA-Z0-9@:%._\ ~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\ .~#?&//=]*)'.'.; DataAnnotation validation failed for 'DynamoDbConfiguration' members: 'Region' with the error: 'The Region field is required.'.
   at Microsoft.Extensions.Options.OptionsFactory`1.Create(String name)

The ValidateDataAnnotations extension method is defined in the Microsoft.Extensions.Options.DataAnnotations NuGet package. For web apps that use the Microsoft.NET.Sdk.Web SDK, this package is referenced implicitly from the shared framework.

more details

  • Related