我有以下DTO,我已经为它做了一些验证规则:
[Route("/warranties/{Id}", "GET, PUT, DELETE")]
[Route("/warranties", "POST")]
public class WarrantyDto : IReturn<WarrantyDto>
{
public int Id { get; set; }
public int StatusId { get; set; }
public string AccountNumber { get; set; }
}
验证规则:
public class WarrantyDtoValidator : AbstractValidator<WarrantyDto>
{
public WarrantyDtoValidator()
{
RuleSet(ApplyTo.Post, () => RuleFor(x => x.AccountNumber).NotEmpty());
RuleSet(ApplyTo.Put, () =>
{
RuleFor(x => x.Id).NotEmpty();
RuleFor(x => x.AccountNumber).NotEmpty();
});
RuleSet(ApplyTo.Delete, () => RuleFor(x => x.Id).NotEmpty());
}
}
在AppHost中设置验证:
Plugins.Add(new ValidationFeature());
container.RegisterValidators(typeof (WarrantyDtoValidator).Assembly);
FluentValidationModelValidatorProvider.Configure(provider =>
{
provider.ValidatorFactory = new FunqValidatorFactory(container);
});
然后当我发布WarrantyDto时,如果我没有输入AccountNumber
,验证似乎不起作用:
[POST("create")]
public ActionResult Create(WarrantyDto model)
{
if (!ModelState.IsValid) return View(model);
_warrantyService.Post(model);
return RedirectToAction("Index");
}
看起来只是点击_warrantyService.Post(model);
而没有尝试首先验证,任何想法?
答案 0 :(得分:3)
我相信ServiceStack会在其Request / Reponse管道中处理一些FluentValidation RuleSet处理。但是,在MVC控制器中,您必须处理传递要使用的RuleSet。您还应该了解如何执行RuleSets中的规则,因为ServiceStack执行规则与“标准”FluentValidation执行规则之间存在差异。
[POST("create")]
public ActionResult Create([CustomizeValidator(RuleSet = "POST")]WarrantyDto model)
{
if (!ModelState.IsValid) return View(model);
_warrantyService.Post(model);
return RedirectToAction("Index");
}