在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
第一种方式单独为每一个Action做验证 // POST api/values public HttpResponseMessage Post([FromBody]UserInfo userInfo) { if (string.IsNullOrWhiteSpace(userInfo.Gender)) { ModelState.AddModelError("Gender", "性别不能为空"); } if (ModelState.IsValid) { // Do something with the product (not shown). return new HttpResponseMessage(HttpStatusCode.OK); } else { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } } public class UserInfo { public int Id { get; set; } [Required] [StringLength(20, ErrorMessage = "名字太长了或者太短了", MinimumLength = 4)] public string Name { get; set; } [RegularExpression(@"([2-5]\d)", ErrorMessage = "年龄在20-50之间")] public int Age { get; set; } public string Gender { get; set; } } 第二种做全局验证: public class ValidationAttribute : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { if (!actionContext.ModelState.IsValid) { actionContext.Response = actionContext.Request.CreateErrorResponse( HttpStatusCode.BadRequest, actionContext.ModelState); } } } WebApiConfig.cs config.Filters.Add(new ValidationAttribute());
|
请发表评论