I have a requirement to return error 400 from an ASP.NET Web API Post request when the Json request contains duplicate keys.
For example, if the request was
{
"key1": "value1",
"key2": 1000,
"key2": 2000,
"key3": "value3"
}
then I would like the error to be selected due to the presence of two "key2" keys.
My controller method looks something like
[HttpPost]
public IHttpActionResult PostMethod([FromBody]RequestModel request)
{
.....
}
and my RequestModel model for example
public class RequestModel
{
[Required]
public string Key1 {get; set; }
[Required]
public int Key2 {get; set; }
public string Key3 {get; set; }
}
In the above example, the Json serializer seems to be happy to accept the request and populate Key2 with 2000 or any other last key instance.
I think I need to do something with the JsonSerializerSettings class or implement a custom JsonConverter, however I'm not sure how to do this.