asp.net model 验证和取出 ErrorMessage 信息

public class Users
    {
        public int Id { get; set; }
        public string Name { get; set; }

        [Required(ErrorMessage = "邮箱不能为空")]
        [EmailAddressAttribute(ErrorMessage = "邮箱格式不正确")]
        public string Email { get; set; }
        [DisplayName("密码")]
        [Required(ErrorMessage = "密码不能为空")]
        public string Password { get; set; }
    }

验证

[HttpPost]
        public IActionResult Get([FromRoute]Users model)
        {
            if (!ModelState.IsValid)
            {
                var sb = new StringBuilder();

                foreach (var key in ModelState.Keys)
                {
                    var state = ModelState[key];
                    if (state.Errors.Any())
                    {
                        sb.Append(state.Errors.First().ErrorMessage + "\n\r");
                    }
                }
                return Ok(sb.ToString());
            }
            return Ok(model);
        }

 

posted @ 2018-01-09 17:33  游子善心  阅读(3)  评论(0编辑  收藏  举报  来源