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?
You will need to define custom Validation Attribute as
likewise in your model class
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.
This answer is not for this case, but it is very relevant if you want to validate a parameter manually:
You can use the
Validate()
method of the ApiController class to manually validate the model and set the ModelState.