一、三种验证方法
1.直接注册验证函数
services.AddOptions<OrderServiceOptions>().Configure(options => { configuration.Bind(options); }).Validate(options => options.MaxOrderCount > 100,"这是错误信息");
2.使用 Microsoft.Extensions.Options.DataAnnotations
a.给模型打上验证标签
public class OrderServiceOptions { [Range(30, 100)] public int MaxOrderCount { get; set; } = 100; }
.b.开启验证
services.AddOptions<OrderServiceOptions>().Configure(options =>
{
configuration.Bind(options);
}).ValidateDataAnnotations();
3.实现 IValidateOptions<TOptions>
a.实现IValidateOptions类
public class OrderServiceValidateOptions : IValidateOptions<OrderServiceOptions> { public ValidateOptionsResult Validate(string name, OrderServiceOptions options) { if (options.MaxOrderCount > 100) { return ValidateOptionsResult.Fail("MaxOrderCount 不能大于100"); } else { return ValidateOptionsResult.Success; } } }
b.服务注册
services.AddOptions<OrderServiceOptions>().Configure(options => {
configuration.Bind(options); }).Services.AddSingleton<IValidateOptions<OrderServiceOptions>>(new OrderServiceValidateOptions( ));