Ben D
Ben D

Reputation: 475

Kestrel & Aspnet Response Buffering

I'm currently building an ASPNet Web Api that needs to stream a response as a string.

public async Task Stream(
        [FromRoute] long id,
        [FromBody] AddConversationMessageRequest request,
        CancellationToken token)
    {
        request.ConversationId = id;

        var httpContext = ControllerContext.HttpContext;
        httpContext.Response.Headers.Append("Content-Type", "text/plain; charset=utf-8");
        httpContext.Response.Headers.Append("X-Content-Type-Options", "nosniff");
        httpContext.Response.Headers.Append("Cache-Control", "no-cache, no-store, must-revalidate");
        httpContext.Response.Headers.Append("Pragma", "no-cache");
        httpContext.Response.Headers.Append("Expires", "0");

        // Disable response buffering
        httpContext.Response.StatusCode = StatusCodes.Status200OK;
        await httpContext.Response.Body.FlushAsync(token);


        await foreach (var response in Mediator.CreateStream(request, token))
        {
            await httpContext.Response.WriteAsync(response.Chunk", token);
            await httpContext.Response.Body.FlushAsync(token);
        }
    }

The code works well except that when calling the API endpoint the result is buffered and only flushed when the string contains a \n\n character.

If I change this line

    await httpContext.Response.WriteAsync(response.Chunk", token);

To

    await httpContext.Response.WriteAsync(${response.Chunk\n\n}", token);

The response gets streamed correctly but of course with trailing \n\n.

I'm not able to find a way to completely disable the buffering or to flush the buffer after each whitespace for example.

Upvotes: 0

Views: 28

Answers (0)

Related Questions