第一种方式单独为每一个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(, ErrorMessage = "名字太长了或者太短了", MinimumLength = )]
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());