Skip to content

Api return IAsyncEnumerable<> get errors when AddJsonOptions with custom json converter extend from JsonConverter<object> #54374

Open

Description

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    Needs: Attention 👋This issue needs the attention of a contributor, typically because the OP has provided an update.area-mvcIncludes: MVC, Actions and Controllers, Localization, CORS, most templates

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions