ModelState errors reported by Microsoft.AspNetCore.Mvc.NewtonsoftJson #33451
Labels
bug
This issue describes a behavior which is not expected - a bug.
feature-model-binding
investigate
old-area-web-frameworks-do-not-use
*DEPRECATED* This label is deprecated in favor of the area-mvc and area-minimal labels
Milestone
Describe the bug
Problem is related to the migration from ASP.NET MVC (.NET Framework 4.8) web application to .NET 5 and is about different amount of errors when parsing wrong JSON request.
In old code we had some JsonFormatter configuration
We have migrated the app and moved to Microsoft.AspNetCore.Mvc.NewtonsoftJson so our settings changed to
We have some API POST endpoint that consumes some data model parsed from json, example:
As you can notice, for "candyCount" there is an incorrect value assigned.
For old app we received error message
In migrated app we get two errors
If I get rid of
AddNewtonsoftJson
call, there is one message again.I have checked the behavior of Newtonsoft.Json for both frameworks by attaching to SerializerSettings.Error delegate and in both cases the same amount of calls is done - it is 3 for such json as above.
If I nest some objects then the number of errors grows by 1 for each level.
There is also some weird property path generated for the errors. While first one does make sense, second one does not as there is no "details" property in type behind the "candyCount" (it is
int
). Type of the property does not matter - for DateTime that I tested error messages were the same.I'm not sure if this is more a bug or a feature - Microsoft.AspNetCore.Mvc.NewtonsoftJson is more exact about number of errors coming from Newtonsoft.Json. On the other hand it does not make to much sense for me to have same multiple errors for one field. There is also the topic of weird key for ModelState entries.
To Reproduce
Sample code is provided here https://github.com/wiesniak/NewtonsoftJsonIssue
There are two similar projects, one for .NET 5 and one for .NET Framework 4.8.
When run, swagger should load with one endpoint. Put the json payload as mentioned above and execute the call. Response should contain errors as described.
Now about the code. There is a class
ModelStateValidationAttribute
(one for each project) that is a global action filter withOnActionExecuting
method override. If you put a breakpoint there and investigate theactionContext.ModelState
you'll see the amount of errors and should notice the difference between projects.Further technical details
dotnet --info
Code was executed via Visual Studio 2019 (16.9.6) but was also observed when app was deployed on Azure Web App.
The text was updated successfully, but these errors were encountered: