.net 如何基于数据注解验证配置?

6yt4nkrj  于 2022-11-19  发布在  .NET
关注(0)|答案(1)|浏览(111)

如何根据我放置的数据注解验证此配置?

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; }
}
sqxo8psd

sqxo8psd1#

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

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

输出量:

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)

ValidateDataAnnotations扩展方法在Microsoft.Extensions.Options.DataAnnotations NuGet包中定义。对于使用Microsoft.NET.Sdk.Web SDK的Web应用程序,此包从共享框架中隐式引用。
更多详细信息

相关问题