Description
openedon Mar 5, 2024
Is there an existing issue for this?
- I have searched the existing issues
Describe the bug
Below is my custom JsonConverter:
public class PlatformObjectJsonConverter : JsonConverter<object>
{
public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
// My Custom Read code logic here
return base.Read(ref reader, typeToConvert, options);
}
public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options)
{
// Let the default.NET behavior handle write object
JsonSerializer.Serialize(writer, value, value.GetType(), removedItSelfOptions);
}
}
Below is my test IAsyncEnumerable api:
[HttpGet]
[Route("TestIAsyncEnumerable")]
public IAsyncEnumerable<string> TestIAsyncEnumerable()
{
return GetAsyncContent();
}
private async IAsyncEnumerable<string> GetAsyncContent()
{
for (var i = 0; i < int.MaxValue; i++)
yield return await Task.Run(() => Guid.NewGuid().ToString());
}
I added it into the mvc JSON options. When I declare API return IAsyncEnumerable<>, my custom PlatformObjectJsonConverter is executed in Write when return the result, which causes errors. I don't want my custom PlatformObjectJsonConverter should treat the IAsyncEnumerable as a value to serialize.
I tried to debug dotnet core should code and found out the reason is that because in SystemTextJsonOutputFormatter, the line if (declaredTypeJsonInfo.ShouldUseWith(runtimeType)) return false, which cause it try to serialize the result with object type in the closest code line await JsonSerializer.SerializeAsync(responseStream, context.Object, SerializerOptions, httpContext.RequestAborted);
Expected Behavior
I expect that my custom JsonConverter should not catch the result returned in api of type IAsyncEnumerable<> to help the api return the result as stream like default behavior
Steps To Reproduce
No response
Exceptions (if any)
No response
.NET Version
8
Anything else?
No response