With ASP.NET Core 10's TypedResults.ServerSentEvents, how do SseItem<T> event types and ids let a build dashboard resume after a reconnect?
answer
- the SseItem<T> overload, not plain T
- constructor takes data and eventType
- EventId and ReconnectionInterval are init-only
- EventType falls back to message
- read Last-Event-ID with [FromHeader]
basics
~20 sYield SseItem<T> objects: the constructor takes the data and an event type, and EventId and ReconnectionInterval are init properties. A reconnecting client sends the last id back in a Last-Event-ID header, which the endpoint binds and uses to replay later events.
solid answer
~40 sUse the `TypedResults.ServerSentEvents<T>(IAsyncEnumerable<SseItem<T>>)` overload. Each `new SseItem<T>(data, eventType)` can carry its own type ("step", "test", "finished") so the browser can route events to different listeners, plus an `EventId` and a `ReconnectionInterval` set with object initializers. Use a sequence number from the build log as the id. When the connection drops, the browser reconnects and sends that id in the `Last-Event-ID` header; bind it with `[FromHeader(Name = "Last-Event-ID")] string? lastEventId` and start the iterator after that sequence, so no step is lost or repeated. `SseItem<T>` throws `ArgumentException` if the type or id contains a line break or the interval is negative, and `EventType` reports `"message"` when none was given. The `IAsyncEnumerable<T>` overload can only apply one type to every event and cannot set ids.
code
csharp · 20 linesapp.MapGet("/builds/{buildId}/events", (string buildId,
[FromHeader(Name = "Last-Event-ID")] string? lastEventId,
BuildLog log, CancellationToken ct) =>
{
var after = long.TryParse(lastEventId, out var seq) ? seq : 0; // resume point
return TypedResults.ServerSentEvents(ReadEvents(log, buildId, after, ct));
});
static async IAsyncEnumerable<SseItem<BuildEvent>> ReadEvents(BuildLog log, string buildId,
long after, [EnumeratorCancellation] CancellationToken ct = default)
{
await foreach (var e in log.ReadAfterAsync(buildId, after, ct)) // replay, then live
{
yield return new SseItem<BuildEvent>(e, eventType: e.Kind) // "step", "test", "finished"
{
EventId = e.Sequence.ToString(),
ReconnectionInterval = TimeSpan.FromSeconds(5)
};
}
}go deeper
Know that SseItem<T> carries an event's data, type and id, and that a reconnecting browser sends the last id back.
Choose the SseItem<T> overload, set EventId and ReconnectionInterval with initializers, and bind Last-Event-ID with [FromHeader] to resume.
Design ids around a replayable, ordered source, handle pruned history explicitly, and use event types to end the stream deliberately.
Weigh the storage and retention cost of replayable event logs against the user impact of gaps after reconnects.
## Why ids matter for a build dashboard A build can run for many minutes. Laptops sleep, Wi-Fi drops, a load balancer recycles a connection. A Server-Sent Events client reconnects on its own, but if the server simply starts the stream again from "now", the dashboard misses every step that finished while it was disconnected, or replays the whole log from the start. The protocol's answer is an **event id**: the client remembers the last id it saw and sends it back when reconnecting. ASP.NET Core 10 exposes this through `SseItem<T>`. ## SseItem<T> in System.Net.ServerSentEvents `SseItem<T>` is a `readonly struct` from the BCL with four members that matter: | Member | How you set it | Notes | |---|---|---| | `Data` | constructor `new SseItem<T>(data, eventType)` | serialized as JSON unless `T` is `string` or `byte[]` | | `EventType` | constructor's optional `eventType` | getter returns `"message"` (`SseParser.EventTypeDefault`) when none was given | | `EventId` | `init` | written as the event's id | | `ReconnectionInterval` | `init` (`TimeSpan?`) | tells the client how long to wait before reconnecting | Validation happens at construction: an event type or id containing a line break throws `ArgumentException`, as does a negative `ReconnectionInterval`. That protects the stream from a value that would otherwise break the event framing. ## Choosing the overload - `ServerSentEvents<T>(IAsyncEnumerable<T>, string? eventType = null)` applies **one** event type to every item and has no way to set ids. - `ServerSentEvents<T>(IAsyncEnumerable<SseItem<T>>)` lets **each** item carry its own type, id and retry hint. It takes no `eventType` argument, because the items carry their own. For resumable streams, always use the second. ## The resume flow in ASP.NET Core 1. The build log assigns each event a monotonically increasing **sequence number**, stored with the event. 2. The endpoint yields `SseItem<BuildEvent>` with `EventId = sequence.ToString()`. 3. The connection drops; the browser reconnects to the same URL and adds a `Last-Event-ID` request header with the last id it received. 4. The endpoint binds that header with `[FromHeader(Name = "Last-Event-ID")] string? lastEventId`, parses it, and starts reading the log **after** that sequence. 5. Events that happened during the gap are delivered first, then the stream continues live. ASP.NET Core has no built-in replay store: the ids are only useful if your source can read "everything after sequence N". A build log in a database or an append-only stream works; an in-memory channel that only carries live events does not. ## How SseFormatter writes each field ASP.NET Core 10 hands every item to `System.Net.ServerSentEvents.SseFormatter`, which writes the fields in a fixed order: 1. an `event:` line, **only** when an event type was actually given (the formatter reads the stored value, not the `EventType` getter, so the `message` default is never written); 2. one `data:` line per line of the payload, with `\r\n` and `\n` normalised; 3. an `id:` line when `EventId` is set; 4. a `retry:` line in **milliseconds** when `ReconnectionInterval` is set; 5. a blank line that ends the event. Because ids and types were already validated by `SseItem<T>`, nothing you put in them can break this framing. ## Event types on the client side Browsers deliver events whose type is the default `message` to the `onmessage` handler; named types such as `step` or `finished` need `addEventListener("step", ...)`. Giving the final event its own type (`finished` or `failed`) lets the dashboard close the connection deliberately instead of letting the browser reconnect after the server ends the response. ## ReconnectionInterval Setting `ReconnectionInterval` on an item writes a retry hint the client uses for its next reconnection delay. You do not need it on every event: set it on the first event, or when you want clients to back off, for example while a build agent is being replaced.
- What should the endpoint do when Last-Event-ID names a sequence the log has already pruned?It cannot replay the gap, so it should tell the client instead of silently skipping events. A common answer is to yield a first event of its own type, such as `reset`, carrying the current build state, and continue live from there; the dashboard reloads its view on that event. Returning an error status is not an option once streaming starts, so the decision must be made before the first item.
- Why is a database sequence number a better event id than a timestamp?Two build events can share a timestamp, and clocks on different instances drift, so "everything after this time" can skip or duplicate events. A monotonically increasing sequence from the log gives a strict order, so resuming after id N returns exactly the events the client has not seen, on whichever instance it reconnects to.
- Pass eventType to the SseItem overload of TypedResults.ServerSentEvents to name each event.
- SseItem<T>.EventType is null when no event type was given.
- ASP.NET Core stores sent events and replays them automatically on reconnect.
- Read the resume point from SseItem.EventId on the incoming request.
- Use DateTime.UtcNow as the event id so reconnects resume by time.
Assumes ASP.NET Core 10, where TypedResults.ServerSentEvents (new in 10) accepts IAsyncEnumerable<SseItem<T>>; SseItem<T> itself is the BCL type from System.Net.ServerSentEvents.