DotNetSseClient 2.0.0

dotnet add package DotNetSseClient --version 2.0.0
                    
NuGet\Install-Package DotNetSseClient -Version 2.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="DotNetSseClient" Version="2.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="DotNetSseClient" Version="2.0.0" />
                    
Directory.Packages.props
<PackageReference Include="DotNetSseClient" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add DotNetSseClient --version 2.0.0
                    
#r "nuget: DotNetSseClient, 2.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package DotNetSseClient@2.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=DotNetSseClient&version=2.0.0
                    
Install as a Cake Addin
#tool nuget:?package=DotNetSseClient&version=2.0.0
                    
Install as a Cake Tool

dotnet-sse-client

A lightweight Server-Sent Events (SSE) client built on HttpClient and IHttpClientFactory, with keyed DI registration for .NET applications.

Requirements

  • .NET 10 (net10.0)
  • .NET 11 (net11.0)

Installation

dotnet add package DotNetSseClient

Quick start

A long-lived stream usually lives in a hosted service. Clients are registered as singletons by default, so they can be injected directly:

using DotNetSseClient;

var builder = Host.CreateApplicationBuilder(args);

builder.Services.AddSingleton<ITokenProvider, MyTokenProvider>();
builder.Services.AddSseClient<MyEvent>(key: "events", baseAddress: "https://api.example.com/")
    .WithBearerToken((serviceProvider, cancellationToken) =>
        serviceProvider.GetRequiredService<ITokenProvider>().GetTokenAsync(cancellationToken))
    .OnUnauthorized(async (serviceProvider, _, cancellationToken) =>
    {
        await serviceProvider.GetRequiredService<ITokenProvider>().RefreshAsync(cancellationToken);
        return true; // retry once with the refreshed token
    });

builder.Services.AddHostedService<EventListener>();
await builder.Build().RunAsync();

sealed class EventListener([FromKeyedServices("events")] SseClient<MyEvent> stream, ILogger<EventListener> logger)
    : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        await stream.StartAsync(
            "sse/updates",
            onMessage: async (message, cancellationToken) => await HandleAsync(message, cancellationToken),
            onError: ex => logger.LogWarning(ex, "SSE error"),
            onDisconnected: () => logger.LogInformation("Disconnected; reconnecting."),
            cancellationToken: stoppingToken);

        // Completes when the host stops; throws SseStreamTerminatedException if the stream gives up.
        await stream.Completion;
    }
}

StartAsync returns as soon as the stream is running in the background. Await Completion to wait for it to end, or call StopAsync to stop it.

Why keyed DI registration?

If you consume two different SSE streams in the same application with the same payload type, register two SseClient<T> instances with different keys and configurations. Registering the same key twice for the same T throws.

Configuration

Builder method Purpose
WithBearerToken(factory) Sends Authorization: Bearer …, fetched on every connection attempt.
WithApiKey(header, key) Sends an API key header on every connection attempt.
OnUnauthorized(handler) Called on HTTP 401; return true to retry once.
WithReconnectPolicy(o => …) Initial, minimum and maximum delay, backoff multiplier, jitter.
WithEventTypes("update", …) Delivers only matching event: types (events without one are message).
WithJsonSerializerOptions(options) Replaces the default JsonSerializerDefaults.Web options.
ConfigureHttpClient(b => …) Access to the underlying IHttpClientBuilder for handlers, resilience, proxies, certificates.

The lifetime can be changed with AddSseClient<T>(key, baseAddress, ServiceLifetime.Scoped).

Trimming and Native AOT

The default overload uses reflection-based System.Text.Json and is annotated accordingly. For trimmed or AOT apps, pass source-generated metadata:

[JsonSerializable(typeof(MyEvent))]
partial class MyJsonContext : JsonSerializerContext;

services.AddSseClient("events", "https://api.example.com/", MyJsonContext.Default.MyEvent);

Behavior notes

  • Endpoints passed to StartAsync can be relative to the base address or absolute.
  • Message handlers can be synchronous (Action<T>) or asynchronous (Func<T, CancellationToken, ValueTask>). An async handler is awaited before the next event is read.
  • Calling StartAsync while a stream is running throws InvalidOperationException. Await StopAsync first. Check IsRunning to see whether a stream is active.
  • The client validates text/event-stream responses and sends Accept: text/event-stream and Cache-Control: no-cache.
  • Reconnects follow the server's retry: field (default 3 s), never faster than MinimumDelay (500 ms). They back off exponentially with jitter, up to MaxDelay (60 s), while attempts keep failing before an event is received. A Retry-After header on 429/503 is honoured.
  • Last-Event-ID is resent on reconnect, and a server can reset it with an empty id field.
  • Retryable failures (network errors, timeouts, 408, 429, 5xx) are reported through the onError callback and followed by a reconnect.
  • Invalid JSON payloads and exceptions thrown by your handlers are reported through onError, and the stream continues.
  • Terminal failures (other 4xx statuses, a refused 401, a wrong content type, a failing request callback) stop the stream. onError receives an SseStreamTerminatedException (with StatusCode when applicable), and Completion faults with the same exception.
  • An HTTP 204 response stops the stream without an error, as the SSE specification requires.
Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed.  net11.0 is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2.0.0 49 11/13/2026
1.2.0 119 10/2/2026
1.1.0 103 10/2/2026

2.0.0: singleton by default with configurable lifetime; IHttpClientFactory integration; exponential reconnect backoff with jitter and Retry-After; Completion/IsRunning and SseStreamTerminatedException for terminal failures; async message handlers; event-type filtering; configurable JSON options and source-generated JsonTypeInfo (AOT-compatible); spec-compliant Last-Event-ID reset; StartAsync throws when already running.