我正在尝试验证模型并获得ModelState
验证错误:
这是我的代码
[HttpPost]
[Route("")]
public async Task<HttpResponseMessage> PostSomething(RequestModel request)
{
var modelErrors = ModelState.Values.SelectMany(v => v.Errors);
}
return Request.CreateResponse(HttpStatusCode.OK);
}
当我调试并观察modelErrors变量时,我得到ErrorMessage =“” 和Exception {“在JSON中找不到必需属性'object_id'。 路径'',第14行,位置1.“}。
RequestModel
中没有定义“自定义错误消息”的痕迹public class RequestModel
{
[JsonProperty("arrival")]
[Required]
public DateTime Arrival { get; set; }
[JsonProperty("departure")]
[Required]
public DateTime Departure { get; set; }
[JsonProperty("object_id")]
[Required(ErrorMessage = "Custom error message")]
public int ObjectId { get; set; }
}
Json请求
{
"arrival": "2018-07-01",
"departure": "2018-07-03"
}
答案 0 :(得分:1)
你必须改变:
[JsonProperty("object_id")]
[Required(ErrorMessage = "Custom error message")]
public int ObjectId { get; set; }
为:
[JsonProperty("object_id")]
[Required(ErrorMessage = "Custom error message")]
public Nullable<int> ObjectId { get; set; }
允许int类型的null
值。