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've written up a filter (as suggested in various comments) that checks the ModelState and throws an exception if serialization errors did occur. Beware though, that this may not contain only serialization exceptions - that could be adjusted by specifing the concrete exception type in the Select
statement.
public class ValidModelsOnlyFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ModelState.IsValid)
{
base.OnActionExecuting(actionContext);
}
else
{
var exceptions = new List();
foreach (var state in actionContext.ModelState)
{
if (state.Value.Errors.Count != 0)
{
exceptions.AddRange(state.Value.Errors.Select(error => error.Exception));
}
}
if (exceptions.Count > 0)
throw new AggregateException(exceptions);
}
}
}
I suggest binding this filter on a global scope. I really can't fathom why it should be ok to ignore deserialization exceptions.