Manually validate Model in Web api controller

前端 未结 4 404
梦毁少年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:21

    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.

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

提交回复
热议问题