6.35Server-Sent Events event handler
Created on Aug 17, 2026~3 min read
The IHttpServerSentEventsEventHandler interface allows you to define pre-processing operations for receiving Server-Sent Events pushed by the server. By implementing this interface, you can create a custom Server-Sent Events event handler, such as the CustomServerSentEventsEventHandler class:
public class CustomServerSentEventsEventHandler : IHttpServerSentEventsEventHandler{ // Action to perform when the connection to the event source is opened void OnOpen(); // Action to perform when data is received from the event source Task OnMessageAsync(ServerSentEventsData serverSentEventsData, CancellationToken cancellationToken); // Action to perform when the connection to the event source fails to open void OnError(Exception exception);}To enable this handler in your application, register the CustomServerSentEventsEventHandler service in the Startup.cs or Program.cs file:
services.TryAddSingleton<CustomServerSentEventsEventHandler>();Next, you can specify this handler when building the HTTP request:
HttpRequestBuilder.ServerSentEvents("https://localhost:7044/HttpRemote/Events" , async (data, token) => { Console.WriteLine(data.Data); await Task.CompletedTask; }) .SetEventHandler<CustomServerSentEventsEventHandler>();HttpRequestBuilder.ServerSentEvents("https://localhost:7044/HttpRemote/Events" , async (data, token) => { Console.WriteLine(data.Data); await Task.CompletedTask; }) .SetEventHandler(typeof(CustomServerSentEventsEventHandler)); // Using the type-based approach