How do you get the validators implementing the Fluentvalidation API in ASP.Net WebAPI

1.3k views Asked by At

Example:

public class UserValidator : AbstractValidator<UserViewModel>
{
    public UserValidator()
    {
        RuleFor(p => p.Username).NotEmpty()
            .WithMessage("Please enter a username.");
    }
}

public class UserController : ApiController
{
    public IHttpActionResult Create(UserViewModel vewModel)
    {
        if (ModelState.IsValid)
        {
            return Ok();
        }

        return BadRequest();
    }
}

Just by providing the UserController.Create() method and UserViewModel object, how can you get the UserValidator object or type?

1

There are 1 answers

0
Yannick Meeus On

You can do two things:

Either inject your validator into the constructor of your controller, like so:

public class UserController : ApiController
{
    private readonly IValidator<UserViewModel> userViewModelValidator;

    public UserController(IValidator<UserViewModel> userViewModelValidator)
    {
        this.userViewModelValidator = userViewModelValidator;
    }
}

And then in your method, call:

var validationResults = this.userViewModelValidator.Validate(vewModel);

You can also just new one up:

public IHttpActionResult Create(UserViewModel vewModel)
{
    var validator = new UserValidator();

    if (validator.validate(vewModel).IsValid)
    {
        return Ok();
    }

    return BadRequest();
}

Alternatively, there is some attribute based validation you can do, which probably aligns more with what you want.

public class UserViewModel
{
    [Validator(typeof(UserValidator))]
    public string UserName { get; set; }
}

You will have to wire it up in your composition root, which for Web.Api projects is your global.asax file, in your Application_Start() method.

protected void Application_Start()
{
    // ..other stuff in here, leave as is
    // configure FluentValidation model validator provider
    FluentValidationModelValidatorProvider.Configure(GlobalConfiguration.Configuration);
}