I have a Blazor Hosted WebAssembly application under .NET8. That means I have a Client, a Server and a Shared projects.
I have the following controller into Server, 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;
}
}
On the razor page into Client, 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 streaming
using 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 = 128000
},
cancellationToken);
await foreach (string? line in lines)
{
chatResponse.response += line;
Stat
eHasChanged();
}
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.html
any ideas?