문제

I have the following DTO which I have made some validation rules for:

[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; }
}

Validation Rules:

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());
    }
}

Set up validation in AppHost:

Plugins.Add(new ValidationFeature());
container.RegisterValidators(typeof (WarrantyDtoValidator).Assembly);
FluentValidationModelValidatorProvider.Configure(provider =>
{
    provider.ValidatorFactory = new FunqValidatorFactory(container);
});

Then when I POST a WarrantyDto, validation doesn't seem to work if I don't enter in an AccountNumber:

[POST("create")]
public ActionResult Create(WarrantyDto model)
{
    if (!ModelState.IsValid) return View(model);

    _warrantyService.Post(model);
    return RedirectToAction("Index");
}

It just seem's to hit the _warrantyService.Post(model); without trying to first validate, any ideas?

도움이 되었습니까?

해결책

I believe ServiceStack takes care of some of the FluentValidation RuleSet handling within it's Request/Reponse pipeline. But, within your MVC Controller you'll have to handle passing the RuleSet you want to use. You should also look into how Rules not within RuleSets are executed as there is a difference between how ServiceStack executes Rules and 'standard' FluentValidation executes Rules.

[POST("create")]
public ActionResult Create([CustomizeValidator(RuleSet = "POST")]WarrantyDto model)
{
    if (!ModelState.IsValid) return View(model);

    _warrantyService.Post(model);
    return RedirectToAction("Index");
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top