【发布时间】: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