dotnet / dotnet/aspnetcore

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

Open
#54,374 4 comments 1 reaction 0 assignees View on GitHub
area-mvc Needs: Attention :wave:
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Describe the bug

Below is my custom JsonConverter:

```
public class PlatformObjectJsonConverter : JsonConverter
{
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 TestIAsyncEnumerable()
{
return GetAsyncContent();
}

private async IAsyncEnumerable 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_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.