Skip to content

🏞️ Sample app for ServerSentEvent result support in minimal APIs

Notifications You must be signed in to change notification settings

captainsafia/minapi-sse

Repository files navigation

Server Sent Events in Minimal APIs

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.

Run the Sample App

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

Sample Endpoints

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

Usage Notes

The TypedResults.ServerSentEvents API allows you to easily send Server-Sent Events (SSE) from your minimal API endpoints. Here's how to use it:

Basic Usage

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");
});

Key Features

String Data vs. JSON Objects

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 intervals

    TypedResults.ServerSentEvents(GetSseItemData<HeartRate>(cancellationToken));

Event Types

Specify the event type using the eventType parameter. Clients can listen for specific event types:

TypedResults.ServerSentEvents(GetHeartRate(cancellationToken), eventType: "heartRate");

Cancellation Support

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
});

License

MIT

About

🏞️ Sample app for ServerSentEvent result support in minimal APIs

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages