Non buffered output in ASP.NET Core 6

Viewed 371

I am trying to achieve a simple streaming (non buffered output) using really basic ASP.NET Core 6 app.

The following simple code should output the hello world text to the client and then close the connection (even by adding the document IHttpResponseBodyFeature option) :

app.MapGet("/a", async (ctx) =>
{
    var gg = ctx.Features.Get<Microsoft.AspNetCore.Http.Features.IHttpResponseBodyFeature>()!;
    gg.DisableBuffering();    
    await ctx.Response.Body.WriteAsync(Encoding.UTF8.GetBytes("Hello, World!"));
    await ctx.Response.Body.FlushAsync();        
    await Task.Delay(2000);
});

This is of course a simple example of a behavior I am trying to achieve.

Simple curl request to the app can show that the hello world text is reaching to the client only after the 2 seconds wait.

On the .NET Framework the following code works as expected:

Response.Clear();
Response.Buffer = false;
Response.BufferOutput = false;
Response.Output.WriteLine("Hello World!");
Response.Output.Flush();
System.Threading.Tasks.Task.Delay(2000).Wait();
Response.End();

Simple curl request shows the "hello world" text shown immediately and after 2 seconds the connection get closed.

Thanks in advance.

1 Answers

After few more tries and searches i came upon the following issue on github :

https://github.com/dotnet/aspnetcore/issues/26565

Using the code there i managed to came up with a simple way for working non buffered output (also works on app.MapGet as shown on the question):

HttpContext.Response.StatusCode = 200;
await using var bodyStream = HttpContext.Response.BodyWriter.AsStream();
await HttpContext.Response.StartAsync();
for (var i = 0; i < 3; i++)
{
    await bodyStream.WriteAsync(Encoding.UTF8.GetBytes(Convert.ToBase64String(new byte[128 * 1])));
    await bodyStream.FlushAsync();
    await Task.Delay(2000);
}

await HttpContext.Response.CompleteAsync();
return Ok();

My app had some middle-ware which made debugging worse, disabling it made everything much simpler on my app/scenario.

Thanks for the comments , i hope this helps.

Related