在Web api控制器中手动验证Model

时间:2015-06-18 06:37:45

标签: asp.net asp.net-mvc asp.net-web-api

我有一个名为'User'的类和一个名为'Name'的属性

public class User
{
    [Required]
    public string Name { get; set; }
}

api控制器方法是

public IHttpActionResult PostUser()
{

       User u = new User();
       u.Name = null;

        if (!ModelState.IsValid)
        return BadRequest(ModelState);

        return Ok(u);
}

如何手动验证User对象,以便ModelState.IsValid向我返回false?

4 个答案:

答案 0 :(得分:15)

您可以使用Validate()类的ApiController方法手动验证模型并设置ModelState

public IHttpActionResult PostUser()
{
    User u = new User();
    u.Name = null;

    this.Validate(u);

    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    return Ok(u);
}

答案 1 :(得分:4)

这个答案不适用于这种情况,但如果您想手动验证参数,则非常相关:

public IHttpActionResult Post(User user)
{
    ModelState.Clear(); // remove validation of 'user'
                        // validation is done automatically when the action
                        // starts the execution

    // apply some modifications ...

    Validate(user); // it adds new keys to 'ModelState', it does not update any keys

    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    // ...
}

答案 2 :(得分:3)

您需要将自定义验证属性定义为

class CustomValidatorAttribute : ValidationAttribute
{
  //custom message in ctor
  public CustomValidator() : base("My custom message") {}
  public CustomValidator(string Message) : base(Message) {}
  public override bool IsValid(object value)
  {
     return !string.IsNullOrWhiteSpace(value.ToString());
  }
  //return a overriden ValidationResult
  protected override ValidationResult IsValid(Object value,ValidationContext validationContext)
  {
     if (IsValid(value)) return ValidationResult.Success;
     var message = "ohoh";
     return new ValidationResult(message);
  }
 }

同样在您的模型类中

public class User
{
  [Required]
  [CustomValidator("error")]
  public string Name { get; set; }
}

答案 3 :(得分:1)

模型应该是ActionMethod的输入参数,ModelState.IsValid将根据您在Model类中设置的属性进行验证,在这种情况下,因为它已设置[必需]它将被验证为空值,< / p>

如果您只是想手动检查是否有值,可以直接查看。

if (user.Name == null) {
  return;
}