3

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?

5
  • Are you getting any error when you are calling backend/heartrate in code? Commented May 12 at 20:28
  • @MuhammadZeeshan No. It works fine with curl and I'm also not getting any error in the browser console when calling from Blazor Commented May 12 at 20:55
  • Is your Blazor WebAssembly app also using .NET 10? Commented May 12 at 22:10
  • @MuhammadZeeshan Yes Commented May 13 at 4:27
  • SSE is one-way from server to client so I don't think you'd be using GetStream... client sends the initial request to create an EventSource, but from then on you need an eventlistener to listen for events coming from the server. Check this for JS solution: developer.mozilla.org/en-US/docs/Web/API/EventSource Commented May 30 at 16:20

1 Answer 1

1

I got it working by calling the SSE like this:

public async Task<HttpResponseMessage> GetHeartRate() { var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "backend/heartrate"); httpRequestMessage.SetBrowserResponseStreamingEnabled(true); httpRequestMessage.Headers.Add("Accept", "text/event-stream"); return await HttpClient.SendAsync(httpRequestMessage, HttpCompletionOption.ResponseHeadersRead); } 

And processing it in Blazor with

private async Task ProcessHeartRate() { var response = await GetHeartRate(); await using var stream = await response.Content.ReadAsStreamAsync(); await foreach (var hb in SseParser.Create(stream).EnumerateAsync()) { FIELD_ON_BLAZOR_PAGE = int.Parse(hb.Data); } await InvokeAsync(StateHasChanged); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.