请求:

public class MyRequest
    {
        [Required(ErrorMessage = "Name参数不能为空")]//Required 验证这个参数不能为空 ErrorMessage:为空时自定义错误信息
        public string Name { get; set; }
 
        [Range(1,100, ErrorMessage="Age参数只能是大于1,小于100")]//Range 验证值只能在某些范围内,只适用于Int类型的字段
        public int Age { get; set; }
 
        [Required(ErrorMessage = "电话号不能为空")]
        [RegularExpression("^[1]+[3,4,5,7,8]+\\d{9}", ErrorMessage = "PhoneNum不合法的电话号码格式")]//RegularExpression 用正则验证字段的合法性,多用于身份证、电话号码、邮箱、等等...
        public string Phone { get; set; }
    }

 

过滤器

 public class RequestValidAttribute : ActionFilterAttribute
    {
        private ILog _log = LogManager.GetLogger(Startup.LogRepository.Name, typeof(RequestValidAttribute));

        public override void OnActionExecuting(ActionExecutingContext actionContext)
        {
            if (actionContext.ModelState.IsValid == false)
            {
                // Return the validation errors in the response body.
                // 在响应体中返回验证错误信息
                var errors = new Dictionary<string, IEnumerable<string>>();
                foreach (var keyValue in actionContext.ModelState)
                {
                    errors[keyValue.Key] = keyValue.Value.Errors.Select(e => e.ErrorMessage);
                }

                actionContext.Result= new JsonResult(new BaseApiResult { Code = "400", Message ="请求验证错误;"+ JsonConvert.SerializeObject(errors) });
            }
        }
    }

 

相关文章:

  • 2021-06-06
  • 2021-07-03
  • 2021-09-27
  • 2021-12-15
  • 2022-01-30
  • 2020-11-18
  • 2022-01-18
猜你喜欢
  • 2022-02-18
  • 2021-09-21
  • 2022-12-23
  • 2020-11-12
  • 2021-11-02
  • 2021-09-12
  • 2022-12-23
相关资源
相似解决方案