【发布时间】:2019-12-07 18:50:12
【问题描述】:
我不确定我是否正确使用了 FluentValidation。我很困惑.. Validator 应该与数据库通信吗?
例如,我有一个端点可以将Item 添加到Order。这是我正在使用的模型和相应的验证器:
public class ItemDto
{
public int ItemId { get; set; }
public int OrderId { get; set; }
public int Quantity { get; set; }
public int Price { get; set; }
}
public ItemValidator(IItemRepository itemRepository, IOrderRepository orderRepository)
{
RuleFor(input => input.Price).GreaterThan(0);
RuleFor(input => input.Quantity).GreaterThan(0);
RuleFor(input => input.ItemId).Must(name => itemRepository.ItemExists(ItemId))
.WithMessage(input => $"Item '{input.ItemId}' doesn't exists");
.Must(name => itemRepository.ItemIsDiscontinued(ItemId))
.WithMessage(input => $"Item '{input.ItemId}' is discontinued");
RuleFor(input => input.OrderId).Must(name => orderRepository.OrderExists(OrderId))
.WithMessage(input => $"Order '{input.OrderId}' doesn't exists");
}
我想知道,这是应该如何使用验证器吗?
另一种方法是检查Controller 中是否存在特定订单或商品,如果存在则返回NotFound()。然后在验证器中我会检查价格、数量以及该项目是否已停产?
我希望将所有检查和验证集中在一个地方,但是如果 Item 不存在,我将返回 400 状态错误并显示“它不存在”(又名 NotFound)消息。
问题是,我应该将“存在验证”放在 Controller 中,而将其余部分放在 Validator 中吗?如果是,验证器中不应该出现的行到底在哪里?
谢谢,
【问题讨论】:
标签: c# validation asp.net-web-api asp.net-core-webapi fluentvalidation