Use correct path for NewtonsoftJson ModelState errors #39058
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Use correct path for NewtonsoftJson ModelState errors
The NewtonsoftJsonInputFormatter has logic that's intended to append the names of missing required properties to the ModelStateDictionary key. Normally, just the ModelName and ErrorContext.Path is used for this key, but ErrorContext.Path does not include the missing required property name like we want it to. For example, given the following class and input missing the required "Name" property:
We will see the following ErrorContext:
So the path used for the ModelStateDictionary key is updated to be "Person.Name" instead of just "Person".
See aspnet/Mvc#8509
However, this logic is caused problems with different JSON deserilization errors that include the member in the path but not at the end. For example, given the following classes and invalid input like
{ "b": { "c": { "d": abc } } }
:We will see the following ErrorContext:
Notice that Member "c" is in the middle of the Path "b.c.d". The error handler gets invoked for each level of nesting. null, "b", "c" and "d" are each a Member in different ErrorContexts all reporting the same parsing error.
The parsing error is reported as a JsonReaderException instead of as a JsonSerializationException like for missing required properties. We use the exception type to filter out these errors and keep the path used for the ModelStateDictionary key as "b.c.d" instead of "b.c.d.c" like before.
Fixes #33451