標籤:
第一種方式單獨為每一個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());
ASP.NET Web API 資料驗證