6.34HttpServerSentEventsBuilder builder
Created on Aug 17, 2026~2 min read
The HttpServerSentEventsBuilder builder is provided by the framework specifically to configure the various settings needed to receive Server-Sent Events pushed by the server. The constructor of HttpServerSentEventsBuilder is private, so it cannot be instantiated directly with the new keyword; however, the framework provides multiple static overload methods of HttpRequestBuilder.ServerSentEvents to create an instance of HttpServerSentEventsBuilder.
HttpRequestBuilder.ServerSentEvents(requestUri, onMessage, configure); // Defaults to a GET requestHttpRequestBuilder.ServerSentEvents(httpMethod, requestUri, onMessage, configure);HttpRequestBuilder.ServerSentEvents(requestUri, configure); // Defaults to a GET requestHttpRequestBuilder.ServerSentEvents(httpMethod, requestUri, configure);In addition, HttpServerSentEventsBuilder provides the following configuration capabilities:
// Defaults to a GET requestHttpRequestBuilder.ServerSentEvents("https://localhost:7044/HttpRemote/Events" , async (data, token) => { Console.WriteLine(data.Data); await Task.CompletedTask; }) // Sets the default reconnection interval; defaults to 2 seconds .SetDefaultRetryInterval(2000) // Unit: milliseconds // Sets the maximum number of retries; defaults to 100 .SetMaxRetries(500) // Sets the action to perform when the connection to the event source is opened .SetOnOpen(() => {}) // Sets the action to perform when data is received from the event source // .SetOnMessage(async (data, token) => {}) // Can be passed in initially // Sets the action to perform when the connection to the event source fails to open .SetOnError(exception => {}) // Sets the Server-Sent Events event handler .SetEventHandler<CustomServerSentEventsEventHandler>() .SetEventHandler(typeof(CustomServerSentEventsEventHandler)) // Sets whether to automatically correct the request method // If true, when the request is GET or HEAD and contains request content, the method is automatically changed to POST; defaults to true .SetAutoCorrectMethod(true) // Sets the HttpRequestBuilder instance .With(builder => {})); // Supports more extensionsAfter successfully building a HttpServerSentEventsBuilder instance through the HttpRequestBuilder.ServerSentEvents method, you can use Send, SendAsync, or SendAsAsyncEnumerable to perform the send operation.
httpRemoteService.Send(httpServerSentEventsBuilder, cancellationToken);await httpRemoteService.SendAsync(httpServerSentEventsBuilder, cancellationToken);await foreach (var data in httpRemoteService.SendAsAsyncEnumerable(httpServerSentEventsBuilder, cancellationToken)){ // Process each item of data}