I have a Blazor Hosted WebAssembly application under .NET8. That means I have a Client, a Server and a Shared projects.
Into Server, I have the following controller, which has a loop which triggers for every new entry the backend service provides:
[HttpPost, Route("/api/chat/communicate_async")]public async IAsyncEnumerable<string> DoCommunicateAsync(ChatRequest chat){ IAsyncEnumerable<string> results = _IChat.DoCommunicateAsync(chat); await foreach (var result in results) { yield return result; }}Into Client, on the razor page, I have the following code to make each loop iteration on the controller be presented into UI:
CancellationToken cancellationToken = GetCancellationToken();var requestContent = new StringContent(System.Text.Json.JsonSerializer.Serialize(chatRequest), Encoding.UTF8, "application/json");using var requestMessage = new HttpRequestMessage(HttpMethod.Post, "api/chat/communicate_async"){ Content = requestContent};requestMessage.SetBrowserResponseStreamingEnabled(true); // Enable response streamingusing var response = await Http.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead);using Stream stream = await response.Content.ReadAsStreamAsync(cancellationToken);var lines = System.Text.Json.JsonSerializer.DeserializeAsyncEnumerable<string>( stream, new JsonSerializerOptions { PropertyNameCaseInsensitive = true, DefaultBufferSize = 128 }, cancellationToken);await foreach (string? line in lines){ chatResponse.response += line; StateHasChanged();}The client seems that is waiting until all iterations are finished in controller in order to make the json loop and update UI. I have read lot of articles so far and tried different things from here: https://www.tpeczek.com/2021/07/aspnet-core-6-and-iasyncenumerable.htmlAnd from here: Streaming lines of text over HTTP with Blazor using IAsyncEnumerableTried already change also DefaultBufferSize but seems this is not the problem as each trigger from controller should trigger the loop in client.
Any ideas?