Manually validate Model in Web api controller

2020-02-29 00:57发布

问题:

I have a class called 'User' and a property 'Name'

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

And api controller method is

public IHttpActionResult PostUser()
{

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

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

        return Ok(u);
}

How do i manually validate the User object so the ModelState.IsValid return false to me?

回答1:

You can use the Validate() method of the ApiController class to manually validate the model and set the ModelState.

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

    this.Validate(u);

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

    return Ok(u);
}


回答2:

This answer is not for this case, but it is very relevant if you want to validate a parameter manually:

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

    // ...
}


回答3:

You will need to define custom Validation Attribute as

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

likewise in your model class

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


回答4:

The model should be an input parameter to your ActionMethod, and ModelState.IsValid will validate as per the attributes you set in the Model class, in this case as it is set [Required] it will be validated againg null values,

and if you just wish to manually check whether there is a value, you can check it directly.

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