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