-
Notifications
You must be signed in to change notification settings - Fork 2.1k
JsonInputFormatter, ModelState and error response message. #4607
Description
I have been digging through the aspnet/mvc issues backlog as well as StackOverflow/Google and I have learned that when a client calls a controller/action that uses [FromBody], the JsonInputFormatter is used rather than the MVC Model binding stuff. This results in ModelState.IsValid returning true even when the model state isn't valid, because the actual model validation occurs as part of the input formatter processing, after the ModelState is already populated. This, of course, is problematic because it doesn't align with other properties like FromRoute where deserialization/parsing errors are included in the ModelState.
I can accept that this is how things work though and move on. The problem I am now running into is that I can't figure out any way to surface the JSON deserializer error in the BadRequest response. Looking at https://github.com/aspnet/Mvc/blob/master/src/Microsoft.AspNet.Mvc.Formatters.Json/JsonInputFormatter.cs#L105, I can see that the ModelState is actually updated (Yay!), unfortunately because the Input Formatter proceeds with surfacing the error through its failure mechanisms as well (https://github.com/aspnet/Mvc/blob/master/src/Microsoft.AspNet.Mvc.Formatters.Json/JsonInputFormatter.cs#L133) there is no opportunity for user code to actually look at the ModelState and report the error it has in the usual ways (HttpBadRequest(ModelState)).
What is the ASP.NET Core 1.0 release plan for this? Unless I am missing something, it seems that I can't really leverage input formatters unless I am okay with never giving a useful response to my users. If I want to give them information to help troubleshoot what is wrong with their request I have to take in a [FromBody] String and deserialize by hand inside each of my actions, or build my own InputFormatter that doesn't actually return an error on failure and instead just populates the ModelState (as JsonInputFormatter does), then claim success.
Also, are there any workarounds short of writing my own input formatter that doesn't behave correctly (always returns success with Model errors)? I also tried adding an exception filter but it doesn't appear to catch InputFormatter problems, which isn't surprising as the ExceptionFilter is much later in the pipeline.