异常信息:"有一个值是必需的,但请求中不存在该值。"异常
现象描述:.net framework 4.5 在webapi的接口方法中,有string类型能数,但允许用户不填写,传默认空值(非null),但服务端接收到“”值会报 "有一个值是必需的,但请求中不存在该值。"异常
处理:在 ApiResultAttribute.cs 里
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ModelState.IsValid == false)
{
return; //相当于不作校验
// Return the validation errors in the response body.
// 在响应体中返回验证错误
var errors = new Dictionary<string, IEnumerable<string>>();
foreach (KeyValuePair<string, ModelState> keyValue in actionContext.ModelState)
{
errors[keyValue.Key] = keyValue.Value.Errors.Select(e => e.ErrorMessage);
}
actionContext.Response =
actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, errors);
}
}
--- end ---