Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually validate Model in Web api controller

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?

like image 859
Muzafar Khan Avatar asked Jun 18 '15 06:06

Muzafar Khan


People also ask

How do you validate a model?

Models can be validated by comparing output to independent field or experimental data sets that align with the simulated scenario.

Which of the following is used to check the validity of a model in web API?

Handling Validation Errors Web API does not automatically return an error to the client when validation fails. It is up to the controller action to check the model state and respond appropriately. If model validation fails, this filter returns an HTTP response that contains the validation errors.


1 Answers

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);
}
like image 67
Jon Susiak Avatar answered Oct 03 '22 23:10

Jon Susiak