FluentValidation / FluentValidation

A popular .NET validation library for building strongly-typed validation rules.
https://fluentvalidation.net
Apache License 2.0
9.09k stars 1.2k forks source link

WebAPI Validator not being found? #577

Closed louieo closed 7 years ago

louieo commented 7 years ago

Hi, I have the following DTO in my WebAPI project decorated with the attribute :

[Validator(typeof(CustomerAddressDTOValidator))]
public class CustomerAddressDTO
{
    public int Id { get; set; }
    public short UnitNumber { get; set; }
    public short StreetNumber { get; set; }
    public string StreetName { get; set; }
    public string StreetType { get; set; }
    public string PostCode { get; set; }
    public string Suburb { get; set; }
    public string State { get; set; }
}

Validator implementation:

public class CustomerAddressDTOValidator : AbstractValidator<CustomerAddressDTO>
{
    public CustomerAddressDTOValidator()
    {
        RuleFor(a => a.StreetName).NotEmpty();
        RuleFor(a => a.StreetName).Length(2, 200);
    }
}

Controller decorated as such:

[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/CustomerAddresses")]
[ValidateModelFilter]
public class CustomerAddressController : ApiController
{

Custom ActionFilterAttribute:

public class ValidateModelFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (actionContext.ModelState.IsValid == false)
        {
            actionContext.Response = actionContext.Request.CreateErrorResponse(
                HttpStatusCode.BadRequest, actionContext.ModelState);
        }
    }
}

...and config is set up like this:

public static class WebApiConfig { public static void Register(HttpConfiguration configuration) { configuration.Filters.Add(new ValidateModelFilter()); FluentValidationModelValidatorProvider.Configure(); }

A breakpoint in ValidateModelFilter.OnActionExecuting works, yet breakpoint is never hit on first line of CustomerAddressDTOValidator and ModelState.IsValid is always true in the Controller action when I expect a validation issue.

Can you please help me with what might be wrong here?

JeremySkinner commented 7 years ago

I'm assuming you're using WebAPI2 rather than the WebApi that's part of AspNetCore?

That call to FluentValidationModelValidatorProvider.Configure(); definitely doesn't look right - the WebApi integration doesn't have a method that takes 0 parameters. Do you definitely have the FluentValidation.WebApi package installed rather than FluentValidation.Mvc5? The Configure method in the WebApi integration requires an HttpConfiguration to be passed as the first parameter:

FluentValidationModelValidatorProvider.Configure(configuration);
louieo commented 7 years ago

I had the WebAPI package installed but was using using FluentValidation.Mvc instead of using FluentValidation.WebApi; in my WebApiConfig class.

All working now. Thanks for the fast reply!