In ASP.NET Core 10, support for SSEs was added. I've adapted the example given there (with some support from this repository).
I can call this code with curl and it returns the expected output:
app.MapGet("/backend/heartrate", (CancellationToken cancellationToken) => { async IAsyncEnumerable<int> GetHeartRate( [EnumeratorCancellation] CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested) { var heartRate = Random.Shared.Next(60, 100); yield return heartRate; await Task.Delay(2000, cancellationToken); } } return TypedResults.ServerSentEvents(GetHeartRate(cancellationToken), eventType: "heartRate"); }); Now I'd like to receive and process SSEs in my Blazor project. Unfortunately, there doesn't seem to be any client code on how to handle that. I've tried the following code, but there always seem to be zero elements in the stream.
private async Task GetHeartRate() { await using var stream = await HttpClient.GetStreamAsync("backend/heartrate"); await foreach(var item in SseParser.Create(stream).EnumerateAsync()) { heartRate = int.Parse(item.Data); } } How do I parse this SSE correctly?