In .NET 10 Preview 3, minimal APIs adds supports for transmitting server-sent events from backend services using the TypedResults
abstraction. This repo demonstrates support for these APIs.
To run the API, run dotnet run
in the repo root.
$ dotnet run
Using launch settings from ~/git/minapi-sse/Properties/launchSettings.json...
Building...
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:5293
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: ~/git/minapi-sse
The sample app includes three endpoints:
/string-item
: Returns string data with heart rate values/json-item
: Returns JSON-serialized heart rate objects/sse-item
: Return unformatted heart rate objects
The TypedResults.ServerSentEvents
API allows you to easily send Server-Sent Events (SSE) from your minimal API endpoints. Here's how to use it:
app.MapGet("/sse-endpoint", (CancellationToken cancellationToken) =>
{
async IAsyncEnumerable<string> GetData(
[EnumeratorCancellation] CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
yield return "Some data";
await Task.Delay(1000, cancellationToken);
}
}
return TypedResults.ServerSentEvents(GetData(cancellationToken), eventType: "update");
});
The API supports both string and object data:
-
Strings: Sent as raw strings without additional formatting
TypedResults.ServerSentEvents(GetStringData<string>(cancellationToken), eventType: "message"); TypedResults.ServerSentEvents(GetStringData<byte[]>(cancellationToken), eventType: "message");
-
JSON: Automatically serialized using the configured JSON serializer
TypedResults.ServerSentEvents(GetJsonData<HeartRate>(cancellationToken), eventType: "data");
-
SseItem: Sent as raw strings or serialized using the configured JSON serializer but wrapped as the
SseItem
to support setting event IDs and reconnection intervalsTypedResults.ServerSentEvents(GetSseItemData<HeartRate>(cancellationToken));
Specify the event type using the eventType
parameter. Clients can listen for specific event types:
TypedResults.ServerSentEvents(GetHeartRate(cancellationToken), eventType: "heartRate");
SSE connections stay open until explicitly canceled. Always include a CancellationToken
to allow proper cleanup. When using minimal APIs, the CancellationToken
can be mapped from the route handler. This token maps to HttpContext.RequestAborted.
app.MapGet("/events", (CancellationToken cancellationToken) => {
// Use the token for cancellation support
});