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?
You can do two things:
Either inject your validator into the constructor of your controller, like so:
And then in your method, call:
You can also just new one up:
Alternatively, there is some attribute based validation you can do, which probably aligns more with what you want.
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.