Skip to content

Consistently serialize child members returned from route handlers #39858

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

Merged
merged 2 commits into from
Jan 31, 2022

Conversation

halter73
Copy link
Member

@halter73 halter73 commented Jan 29, 2022

The comments show the response bodies produced by the following route handlers before and after the PR.

var app = WebApplication.Create(args);

// Before: { "p": "p" }
// After: { "c": "c", "p": "p" }
app.MapGet("/task", () => Task.FromResult<Parent>(new Child()));
app.MapGet("/valuetask", ValueTask<Parent> () => new(new Child()));

// Before: { "c": "c", "p": "p" }
// After: { "c": "c", "p": "p" }
app.MapGet("/", Parent () => new Child());

// Before: { "c": "c", "p": "p" }
// After: { "c": "c", "p": "p" }
app.MapGet("/taskobj", () => Task.FromResult<object>(new Child()));
app.MapGet("/valuetaskobj", ValueTask<object> () => new(new Child()));

app.Run();

record Parent(string P = "p");
record Child(string C = "c") : Parent;

This shows an inconsistency in how returned objects are serialized in async methods that return a Task<Parent> or ValueTask<Parent> vs non-async methods that return Parent when the runtime type is a child type.

The non-async route handler has the right behavior because it results in a call to WriteAsJsonAsync<object>(...) instead of WriteAsJsonAsync<Parent>(...) which is what gets called in the async case. See https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-polymorphism

Fixes #39856

@davidfowl
Copy link
Member

This change doesn't feel right to me but I understand the current inconsistency with the IResult type.

@halter73 halter73 enabled auto-merge (squash) January 31, 2022 20:27
@halter73 halter73 merged commit 088595a into main Jan 31, 2022
@halter73 halter73 deleted the halter73/39856 branch January 31, 2022 22:23
@ghost ghost added this to the 7.0-preview1 milestone Jan 31, 2022
@wtgodbe wtgodbe modified the milestones: 7.0-preview1, 7.0-preview2 Jan 31, 2022
@amcasey amcasey added area-networking Includes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractions and removed area-runtime labels Aug 24, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area-networking Includes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractions
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Async minimal route handlers don't serialize child members
6 participants