三种验证的代码:
// 直接注册验证函数
services.AddOptions<OrderServiceOptions>().Configure(options =>
{
configuration.Bind(options);
}).Validate(options =>
{
return options.MaxOrderCount <= 100;
}, "MaxOrderCount 不能大于 100");
// IValidateOptions
services.AddOptions<OrderServiceOptions>().Configure(options =>
{
configuration.Bind(options);
}).Services.AddSingleton<IValidateOptions<OrderServiceOptions>>(new OrderServiceValidateOptions());
// 属性验证
services.AddOptions<OrderServiceOptions>().Configure(options =>
{
configuration.Bind(options);
}).ValidateDataAnnotations();
OrderServiceValidateOptions:
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;
}
}
}
属性验证需要配合 DataAnnotations 使用:
public class OrderServiceOptions
{
[Range(30, 100)]
public int MaxOrderCount { get; set; } = 100;
}