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?
Models can be validated by comparing output to independent field or experimental data sets that align with the simulated scenario.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With