【问题标题】:How to validate IEnumerable of a class within another IEnumerable of a class using fluent validation如何使用流利的验证在一个类的另一个 IEnumerable 中验证一个类的 IEnumerable
【发布时间】:2020-04-13 08:44:34
【问题描述】:

我有这些课程

public class CryptocurrencyDto
{
    public int RequestId { get; set; }
    public IEnumerable<Cryptocurrency> Cryptocurrencies { get; set; }
}

public class Cryptocurrency : BaseClass
{
    public string Ticker { get; set; }
    public string Name { get; set; }
    public double TotalSupply { get; set; }
    public double CirculatingSupply { get; set; }
    public IEnumerable<Note> Notes { get; set; }
}

public class Note
{
    public int NoteId { get; set; }
    public string Description { get; set; }
    public IEnumerable<Url> Urls { get; set; }
    public byte Image { get; set; }
    public int DisplayOrder { get; set; }
}

public class Url
{
    public string UrlId { get; set; }
    public string Link { get; set; }
    public string Description { get; set; }
}

我有这个端点

    [HttpPost]
    public void Post([FromBody] CryptocurrencyDto cryptocurrency)
    {

    }

如何通过这些类进行验证?到目前为止我只知道如何验证第一类CryptocurrencyDto。我不知道如何到达其他班级。加密货币、笔记和网址。

【问题讨论】:

  • 如果有帮助,请将答案标记为已接受,否则请发表评论。

标签: c# asp.net-core asp.net-web-api asp.net-web-api2 fluentvalidation


【解决方案1】:

当您将 FluentValidation 添加到问题标签时,这是使用 FluentValidation 的 Collection Validation

public class CryptocurrencyDtoValidator : AbstractValidator<CryptocurrencyDto> {
  public CryptocurrencyDtoValidator() {
    RuleForEach(x => x.Cryptocurrency).NotNull();
  }
}

More info

但还有许多其他方法可以对关联类使用验证(例如 TIEnumerable&lt;T&gt;):

  1. 创建和使用ValidationAttribute:More info

  2. 实现IValidatableObject:More info

  3. 检查Controller 级别中的所有关联类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 2011-10-12
    • 1970-01-01
    • 2012-11-21
    • 1970-01-01
    相关资源
    最近更新 更多