asp.net 中无法获得所需的模型验证错误消息

Unable to get desired model validation error message in asp.net

我正在尝试验证模型并遇到 ModelState 个验证错误:

这是我的代码

[HttpPost]
[Route("")]
public async Task<HttpResponseMessage> PostSomething(RequestModel request)
{
     var modelErrors = ModelState.Values.SelectMany(v => v.Errors);
}

return Request.CreateResponse(HttpStatusCode.OK); 
}

When I debug and watch modelErrors variable I get ErrorMessage = "" and for Exception {"Required property 'object_id' not found in JSON. Path '', line 14, position 1."}.

在 RequestModel

中没有定义 "Custom error message" 的踪迹
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"
}

您必须更改:

[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; }

允许 null int 类型的值。