Search code examples
c#asp.net-core-webapiasp.net-core-8iasyncenumerable

How to disable IAsyncEnumerable Buffering in ASP.NET Core 8.0 Web API?


I have the following API endpoint:

[HttpGet("test")]
public async IAsyncEnumerable<int> GetStrings()
{
    Random rnd = new();

    foreach (var i in Enumerable.Range(0, 10))
    {
        await Task.Delay(500);
        yield return rnd.Next(100) ;
    }
}

What I expect is to get a stream of numbers every 500ms, but this is not happening, instead it returns to the client after 5 seconds with the whole payload.

So, how to make this code stream these numbers? I use .NET 8.0.


Solution

  • So, how to make this code stream these numbers? I use .NET 8.0.

    This is related with how you send the request. According to the article, it said When using System.Text.Json formatter, MVC relies on the support that System.Text.Json added to stream the result..

    If your application use the right package System.Text.Json and make sure the response header is the application/json. Then you will get a stream of numbers every 500ms.

    You could check it by using the F12 development's network tab.

    The reason why you found it just show all the numbers is according to your browser feature, but inside the network tab it's a steam of numbers.

    Result:

    enter image description here

    enter image description here