如何在ASP.Net WebAPI中获得验证器实现Fluentvalidation API

时间:2015-06-09 12:06:46

标签: c# asp.net-web-api fluentvalidation modelmetadataprovider

示例:

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

只需提供UserController.Create()方法和UserViewModel对象, 如何获取UserValidator对象或输入?

1 个答案:

答案 0 :(得分:0)

你可以做两件事:

将验证器注入控制器的构造函数中,如下所示:

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

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

然后在你的方法中,请致电:

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

你也可以新上一个:

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

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

    return BadRequest();
}

或者,您可以执行一些基于属性的验证,这可能与您想要的更符合。

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

您必须在您的Application_Start()方法中,在组合根中连接它,对于Web.Api项目,这是您的global.asax文件。

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