1.17 选项框架:为选项数据添加验证.pdf

    三种验证的代码:

    1. // 直接注册验证函数
    2. services.AddOptions<OrderServiceOptions>().Configure(options =>
    3. {
    4. configuration.Bind(options);
    5. }).Validate(options =>
    6. {
    7. return options.MaxOrderCount <= 100;
    8. }, "MaxOrderCount 不能大于 100");
    9. // IValidateOptions
    10. services.AddOptions<OrderServiceOptions>().Configure(options =>
    11. {
    12. configuration.Bind(options);
    13. }).Services.AddSingleton<IValidateOptions<OrderServiceOptions>>(new OrderServiceValidateOptions());
    14. // 属性验证
    15. services.AddOptions<OrderServiceOptions>().Configure(options =>
    16. {
    17. configuration.Bind(options);
    18. }).ValidateDataAnnotations();

    OrderServiceValidateOptions:

    1. public class OrderServiceValidateOptions : IValidateOptions<OrderServiceOptions>
    2. {
    3. public ValidateOptionsResult Validate(string name, OrderServiceOptions options)
    4. {
    5. if (options.MaxOrderCount > 100)
    6. {
    7. return ValidateOptionsResult.Fail("MaxOrderCount 不能大于100");
    8. }
    9. else
    10. {
    11. return ValidateOptionsResult.Success;
    12. }
    13. }
    14. }

    属性验证需要配合 DataAnnotations 使用:

    1. public class OrderServiceOptions
    2. {
    3. [Range(30, 100)]
    4. public int MaxOrderCount { get; set; } = 100;
    5. }