I\'m using WebAPI v2.2 and I am getting WebAPI to deserialise JSON onto an object using [FromBody] attribute. The target class of the deserialisation has a [OnDeserialized]
I had exactly the same problem and bookmarked your question in hope that someone would provide a solution. I thought using ModelState implied rewriting some validations in the JSON model, but it just works, in fact it's simple and very well done. I didn't have to modify the model, just the controllers.
My code from one of my controllers, StdResponse being the class used to provide the response with details if needed (in this case, for instance) :
[HttpPost]
public StdResponse Test([FromBody]StdRequest request)
{
if (ModelState.IsValid)
{
//Work on the data from the request...
}
else
{
//Retrieve the exceptions raised during deserialization
var errors = ModelState.SelectMany(v => v.Value.Errors.Select(e => e.Exception));
List messages = new List();
foreach (Exception e in errors)
{
messages.Add(e.GetType().ToString() + ": " + e.Message);
}
return new StdResponse(exchangeVersion, "null", ExecutionResponse.WithError("StdRequest invalid", messages));
}
}