Manually validate Model in Web api controller

前端 未结 4 515
梦毁少年i
梦毁少年i 2020-12-31 20:24

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

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

And api co

4条回答
  •  没有蜡笔的小新
    2020-12-31 21:06

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

提交回复
热议问题