【问题标题】:Validate nested properties with fluent validation request sent from swagger使用从 swagger 发送的流畅验证请求验证嵌套属性
【发布时间】:2021-08-13 09:33:21
【问题描述】:

我正在尝试使用 swagger 发送 [HttpPost],我已使用流式验证将验证属性放置在子属性中。

但是流畅的验证忽略了验证规则。

我的班级的基本结构如下:

public class ChargeCreateRequestModel
{
    public int? CustomerId { get; set; }
    public IList<TaxRequestModel> Taxes { get; set; }

}

public class TaxRequestModel
{
    public string Zip { get; set; }
    public string Plus4 { get; set; }
}

为嵌套类属性设置的验证规则:


public class TaxValidator : AbstractValidator<TaxRequestModel>
{
    public TaxValidator()
    {

        RuleFor(x => x.Zip)
            .NotEmpty()
            .Must(IsAllDigits)
            .Length(5);
    }

    private bool IsAllDigits(string arg)
    {
        return int.TryParse(arg, out _);
    }
}

控制器:

[HttpPost]
[ProducesResponseType(typeof(ApiResponse<string>), (int)HttpStatusCode.OK)]
public async Task<ActionResult> CreateCharge([FromBody] ChargeCreateRequestModel requestModel)
{
    await _chargeService.CreateChargeAsync(requestModel);
    return Ok(new ApiResponse<string>($"List of charge"));
}

如果嵌套属性为 null 或带有任何字符串,则验证始终成功。验证被忽略。

在从 swagger 发布时,我应该使用什么方法来使验证适用于具有流畅验证的嵌套属性?

【问题讨论】:

    标签: c# swagger fluentvalidation asp.net-core-5.0


    【解决方案1】:

    您应该为 ChargeCreateRequestModel 实现验证器

    【讨论】:

    • 我应该包括什么?
    • 因为我已经为其他领域实现了这一点,我没有在问题中发布。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多