我正在探索使用 FluentValidation,因为它似乎是一个优雅的 API,用于在模型绑定时验证我的 ViewModel。我正在寻找有关如何使用此库以及从我的业务(服务)层正确集中验证并将其提升到视图的意见,而无需使用 2 种不同的方法来添加模型状态错误。
我愿意使用完全不同的 API,但本质上是想解决这个分支验证策略。
[旁注:我尝试的一件事是将我的业务方法移动到我的 FluentValidation 的自定义 RsvpViewModelValidator 类中并使用 .Must 方法,但在那里隐藏该调用似乎是错误的,因为如果我需要实际使用我的 Customer 对象,我将拥有重新查询它,因为它超出了范围]
示例代码:
[HttpPost]
public ActionResult AcceptInvitation(RsvpViewModel model)
{
//FluentValidation has happened on my RsvpViewModel already to check that
//RsvpCode is not null or whitespace
if(ModelState.IsValid)
{
//now I want to see if that code matches a customer in my database.
//returns null if not, Customer object if existing
customer = _customerService.GetByRsvpCode(model.RsvpCode);
if(customer == null)
{
//is there a better approach to this? I don't like that I'm
//splitting up the validation but struggling up to come up with a
//better way.
ModelState.AddModelError("RsvpCode",
string.Format("No customer was found for rsvp code {0}",
model.RsvpCode);
return View(model);
}
return this.RedirectToAction(c => c.CustomerDetail());
}
//FluentValidation failed so should just display message about RsvpCode
//being required
return View(model);
}
[HttpGet]
public ActionResult CustomerDetail()
{
//do work. implementation not important for this question.
}