Where can you find model binding errors in ASP.NET Core MVC?
As you stated, ASP.NET MVC core has changed the way MVC API handles model binding by default. You can use the current ModelState to see which items failed and for what reason.
[HttpPatch]
[Route("Test")]
public IActionResult PostFakeObject([FromBody]Test test)
{
foreach (var modelState in ViewData.ModelState.Values)
{
foreach (var error in modelState.Errors)
{
//Error details listed in var error
}
}
return null;
}
}
The exception stored within the error message will state something like the following:
Exception = {Newtonsoft.Json.JsonReaderException: Could not convert string to integer: pie. Path 'age', line 1, position 28. at Newtonsoft.Json.JsonReader.ReadInt32String(String s) at Newtonsoft.Json.JsonTextReader.FinishReadQuotedNumber(ReadType readType) ...
However, as posted in the comments above, the Microsoft docs explains the following:
If binding fails, MVC doesn't throw an error. Every action which accepts user input should check the ModelState.IsValid property.
Note: Each entry in the controller's ModelState property is a ModelStateEntry containing an Errors property. It's rarely necessary to query this collection yourself. Use ModelState.IsValid instead. https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding