Asp.net api Endpoint, IAsyncEnumerable stream being buffered

ideplotest 0 Reputation points
2023-10-15T18:58:45.21+00:00

Hello, I'm using .net 7, http://asp.net core api w/controllers and I"ve tried with minimal api on VS 2022. Using c# to stream using IAsyncEnumerable some simple text line by line. Ive tried a simple obj. Ive tried ints. No matter what I've tried the response keeps getting buffered.

Here's the code Im testing with:

[HttpGet("numbers")]  
public async IAsyncEnumerable<Wrapper> GetNumbers()  
{        
	await foreach(var r in FetchItems())      
	{                         
		yield return  r;     
	}  
}  

static async IAsyncEnumerable<Wrapper> FetchItems()  
{      
	Wrapper wrapper = new Wrapper();      
	for (int i = 1; i <= 10; i++)      
	{           
		wrapper.Number = i;           
		wrapper.Content = "Content " + i;          
		await Task.Delay(300);          
		yield return wrapper;      
	}  
}

****
public class Wrapper 
{     
	public int Number { get; set; }     
	public string Content { get; set; } 
}
Microsoft Edge
Microsoft Edge
A Microsoft cross-platform web browser that provides privacy, learning, and accessibility tools.
2,174 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,242 questions
ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
306 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 57,966 Reputation points
    2023-10-15T19:42:43.1433333+00:00

    Of course it’s buffered. To return the GetNumbers as json, the collection must be read, converted to a json string content, the length of the content sent as a header, then the content itself.

    If you want unbuffered output the your api will need to write to the response stream directly, and flush between items. See long polling. But nowdays a websocket which is packet oriented is a better approach.


  2. ideplotest 0 Reputation points
    2023-10-15T23:57:15.2933333+00:00

    I just realized that it works perfectly in Chrome, but in Edge and in Swagger it buffers. Not sure whats up, but man 2 days trying to figure this out.