Manually validate a model in a web api controller

I have a class called "User" and the property "Name"

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

And api controller method

public IHttpActionResult PostUser()
{

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

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

        return Ok(u);
}

How to manually check a User object so that ModelState.IsValid returns false to me?

+4
source share
4 answers

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

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

    this.Validate(u);

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

    return Ok(u);
}
+14
source

This answer is not for this case, but it is very important if you want to check the 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);
    }

    // ...
}
+4
source

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

The model should be an input parameter for your ActionMethod, and ModelState.IsValid will be checked according to the attributes set in the Model class, in this case, since it is set [Required], it will be checked taking into account zero values,

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

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

All Articles