In this lesson, you will learn how to implement Server-Sent Events (SSE) to push continuous, one-way data updates from your ASP.NET Core server to a Blazor client using a lightweight, standard HTTP stream.
Understanding Server-Sent Events
While SignalR is excellent for full-duplex communication, it can be heavy for simple, unidirectional notifications like live stock tickers or server-side progress bars. SSE is a lightweight alternative that keeps a single HTTP connection open, allowing the server to push text-based data frames whenever new information is available.
Implementation in ASP.NET Core
To stream data, you set the Content-Type to text/event-stream and keep the response body open. Here is how you can implement a basic streaming endpoint in a minimal API:
app.MapGet("/events", async (HttpContext context) =>
{
context.Response.Headers.Add("Content-Type", "text/event-stream");
for (int i = 0; i < 10; i++)
{
await context.Response.WriteAsync($"data: Update #{i}\n\n");
await context.Response.Body.FlushAsync();
await Task.Delay(1000); // Simulate event interval
}
});
Consuming with the Browser API
Because SSE is a browser standard, you don’t need a specialized client library. In a Blazor component, you can use the EventSource JavaScript API to listen for these updates. You can trigger this via IJSRuntime to establish the connection:
// Inside your Blazor Component
protected override async Task OnInitializedAsync()
{
await JS.InvokeVoidAsync("setupEventSource", DotNetObjectReference.Create(this));
}
[JSInvokable]
public void ReceiveUpdate(string message) => Console.WriteLine(message);
On the JavaScript side, you simply point to your endpoint:
window.setupEventSource = (dotNetHelper) => {
const source = new EventSource("/events");
source.onmessage = (event) => {
dotNetHelper.invokeMethodAsync('ReceiveUpdate', event.data);
};
};
Why Use This?
SSE automatically handles reconnection logic for you, making it more resilient than manually polling an API. By using FlushAsync, you ensure that data packets are pushed to the client immediately without buffering, providing a smooth, real-time experience with minimal overhead.
Key Takeaway: Server-Sent Events provide a native, efficient, and unidirectional way to stream server data to the client using a persistent HTTP connection.