ASP.NET Core 3.1: Newtonsoft.Json Issues With Enumerable.Empty<T> Assignment
We’ve spotted some strange behavior before with ASP.NET Core and JSON serialization/deserialization, and I eventually made it back to trying out some scenarios.
One thing we’ve noticed is
Newtonsoft.Json having issues with
Enumerable.Empty<T>() assignments. We typically assign
IEnumerable<T> items with a starting (empty, itemless) collection to avoid a potential
When ran directly it throws a
JsonSerializationException. When ran through
TestServer it returns a 400 Bad Request.
A fix, as mentioned by Bill Boga and demonstrated via tests (see https://github.com/kendaleiv/AspNetCoreJsonTests/commit/8a538f8a6d8d32b68c4eb331dddee9792ada8372), is to install the
Newtonsoft.Json package manually, even if it’s not absolutely necessary for the project to compile.
We can change all usages of
Enumerable.Empty<T>() to something else, like
Array.Empty<T>(), etc. This makes everything just work the way you’d expect.
Tests associated with this post are at: