I am trying to validate a model and get ModelState
validation errors:
Here is my code
[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."}.
There is no trace of "Custom error message" defined in 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 request
{
"arrival": "2018-07-01",
"departure": "2018-07-03"
}
You will have to change:
[JsonProperty("object_id")]
[Required(ErrorMessage = "Custom error message")]
public int ObjectId { get; set; }
to:
[JsonProperty("object_id")]
[Required(ErrorMessage = "Custom error message")]
public Nullable<int> ObjectId { get; set; }
to allow null
values for int type.