0

例子:

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 对象或类型?

4

1 回答 1

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

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

protected void Application_Start()
{
    // ..other stuff in here, leave as is
    // configure FluentValidation model validator provider
    FluentValidationModelValidatorProvider.Configure(GlobalConfiguration.Configuration);
}
于 2015-06-09T12:27:27.243 回答