-
Notifications
You must be signed in to change notification settings - Fork 4.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Properties defined in inherited interface sometimes fail to serialize #56204
Comments
This is due to the JSON serializer not supporting polymorphic serialization. This is supported in .NET 6 with additional configuration #30083 (comment). |
I couldn't figure out the best area label to add to this issue. If you have write-permissions please help me learn by adding exactly one area label. |
Note that polymorphism support has been cut from .NET 6 and the feature will likely be delivered in .NET 7. In the meantime, using a custom converter that implements polymorphism is the only workaround. Duplicate of #30083. |
Do we have a sample that we can document and point people at? |
There are a few workarounds floating around in the wild, although they typically come with too many gotchas and/or security issues for us to give an implicit seal of approval. The simplest way to do polymorphism drawing from the sample above is probably the following: public class VehicleConverter : JsonConverter<IVehicle>
{
public override IVehicle Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
=> throw new NotSupportedException("Polymorphic deserialization not supported in this model.");
public override void Write(Utf8JsonWriter writer, IVehicle vehicle, JsonSerializerOptions options)
{
switch(vehicle)
{
case ICar car:
writer.WriteStartObject();
writer.WriteNumber(nameof(ICar.NumberOfWheels), car.NumberOfWheels);
writer.WriteNumber(nameof(ICar.Speed), car.Speed);
writer.WriteEndObject();
break;
case IScooter scooter:
writer.WriteStartObject();
writer.WriteString(nameof(IScooter.Color), scooter.Color);
writer.WriteNumber(nameof(IScooter.Speed), scooter.Speed);
writer.WriteEndObject();
break;
default:
writer.WriteStartObject();
writer.WriteNumber(nameof(IVehicle.Speed), vehicle.Speed);
writer.WriteEndObject();
break;
};
}
} |
Describe the bug
Suppose you have
ICar
which inherits fromIVehicle
. WhenICar
is used as the return type from a controller action, it is serialized correctly.But if a class
CarWrapper
has a property of typeICar
, whenCarWrapper
is used as the return type from a controller action, the properties defined in IVehicle fail to serialize.To Reproduce
An example can be found here https://github.com/insolublemaize/aspnetcore-serialization-bug. Run the project and go to
/vehicle/GetCar
and/vehicle/GetCarWrapper
to see the difference between the serialized car objects.The relevant section of code is:
Further technical details
dotnet --info
:The text was updated successfully, but these errors were encountered: