In ASP.NET Core 10, how do you stream Server-Sent Events with TypedResults.ServerSentEvents, and what does the result set up for you?
answer
- new result type in .NET 10
- IAsyncEnumerable<T> in, events out
- ServerSentEventsResult<T>
- headers plus DisableBuffering
- JSON via Http.Json JsonOptions
basics
~10 sReturn TypedResults.ServerSentEvents(items), where items is an IAsyncEnumerable<T> or IAsyncEnumerable<SseItem<T>>. The ServerSentEventsResult<T> sets the event-stream and no-cache headers, disables buffering, serializes each item as JSON (strings raw) and writes it as it is yielded.
solid answer
~30 sASP.NET Core 10 added `TypedResults.ServerSentEvents`, which takes an `IAsyncEnumerable<T>` (optionally with one `eventType` for all items) or an `IAsyncEnumerable<SseItem<T>>` and returns a `ServerSentEventsResult<T>`. When it executes it sets `Content-Type: text/event-stream`, `Cache-Control: no-cache,no-store`, `Pragma: no-cache` and `Content-Encoding: identity`, calls `DisableBuffering()` on `IHttpResponseBodyFeature`, then enumerates your sequence and writes one event per item through `System.Net.ServerSentEvents.SseFormatter`, passing `RequestAborted` as the cancellation token. Strings and `byte[]` are written as-is; anything else is serialized with the `Microsoft.AspNetCore.Http.Json.JsonOptions` you set through `ConfigureHttpJsonOptions`, even when a controller returns it. It works from Minimal APIs and MVC actions alike; `Results.ServerSentEvents` is the `IResult`-typed twin.
code
csharp · 17 linesapp.MapGet("/builds/{buildId}/progress",
(string buildId, BuildStatusStore store, CancellationToken ct) =>
TypedResults.ServerSentEvents(WatchAsync(store, buildId, ct), eventType: "progress"));
static async IAsyncEnumerable<BuildProgress> WatchAsync(
BuildStatusStore store, string buildId, [EnumeratorCancellation] CancellationToken ct = default)
{
while (true)
{
var progress = await store.GetProgressAsync(buildId, ct);
yield return progress; // one SSE event, JSON-serialized
if (progress.PercentComplete == 100) yield break;
await Task.Delay(TimeSpan.FromSeconds(1), ct);
}
}
public sealed record BuildProgress(string BuildId, string Step, int PercentComplete);go deeper
Know that ASP.NET Core 10 streams SSE with TypedResults.ServerSentEvents over an IAsyncEnumerable and that each yielded item becomes one event.
Walk through what ServerSentEventsResult<T> does: the headers it sets, DisableBuffering, JSON with the Http.Json options and raw strings.
Explain why validation must happen before the first event, why controller JSON settings may not apply, and how failures are signalled once streaming has begun.
Decide when the built-in result is enough and when a hand-written stream or SignalR better serves the dashboard's needs.
## What changed in ASP.NET Core 10 Server-Sent Events (SSE) is a one-way push channel: the client makes one HTTP request and the server keeps the response open, writing events as they happen. Before .NET 10, ASP.NET Core had no dedicated API, so you set headers and wrote the event text by hand. **ASP.NET Core 10 added `TypedResults.ServerSentEvents`**, a result type that turns an `IAsyncEnumerable` into an event stream. It is a natural fit for a continuous-integration dashboard that shows each build step as it finishes. The event model comes from the BCL namespace `System.Net.ServerSentEvents`: `SseItem<T>` represents one event and `SseFormatter` writes events to a stream. ## The overloads | Call | Returns | Use when | |---|---|---| | `TypedResults.ServerSentEvents(IAsyncEnumerable<string>, string? eventType = null)` | `ServerSentEventsResult<string>` | the payload is already text | | `TypedResults.ServerSentEvents<T>(IAsyncEnumerable<T>, string? eventType = null)` | `ServerSentEventsResult<T>` | objects, one event type for all | | `TypedResults.ServerSentEvents<T>(IAsyncEnumerable<SseItem<T>>)` | `ServerSentEventsResult<T>` | per-event types, ids or retry hints | `Results.ServerSentEvents` offers the same three overloads typed as `IResult`. Returning the concrete `ServerSentEventsResult<T>` lets the endpoint describe itself: the result adds metadata saying the endpoint produces `200` with `text/event-stream`. ## What ExecuteAsync does, in order 1. Sets `Content-Type: text/event-stream`. 2. Sets `Cache-Control: no-cache,no-store` and `Pragma: no-cache`, so caches do not store the stream. 3. Sets `Content-Encoding: identity`, which makes the response compression middleware leave the response alone. 4. Calls `DisableBuffering()` on `IHttpResponseBodyFeature`, so servers and wrappers that buffer (IIS, the compression body) pass each write through. 5. Enumerates your sequence and writes each item with `SseFormatter.WriteAsync`, passing `HttpContext.RequestAborted`; a disconnected client cancels the pending write, and your iterator stops waiting only if that token reaches it, which is why the handler passes its own `CancellationToken` in. Because the status (`200`) and headers go out with the first write, the response cannot later become a `404` or a ProblemDetails body; validate the build id **before** returning the result. ## Serialization rules - `string` items are written as raw text, not as JSON strings with quotes. - `byte[]` items are written as raw bytes. - Any other `T` is serialized with `System.Text.Json` using **`Microsoft.AspNetCore.Http.Json.JsonOptions`**, the options `builder.Services.ConfigureHttpJsonOptions(...)` configures. That holds even when an MVC action returns the result, so MVC's `AddJsonOptions` settings do **not** apply. - A runtime type more derived than `T` is serialized polymorphically only if `T`'s type info supports it; otherwise it falls back to `object`'s. ## Minimal APIs and controllers The release notes state the result is supported in both. In a Minimal API, return it from the handler; in a controller, return it from an action typed as `IResult` or `ServerSentEventsResult<T>`. In ASP.NET Core 10 the result also carries metadata that stops cookie authentication from redirecting the request to a login page, so an expired session gets `401` rather than an HTML redirect the event-stream client cannot use. ## What the result does not do The result is deliberately small. Knowing its edges saves a design review: - **No heartbeats.** It writes only events you yield; an idle build produces no bytes at all. - **No replay.** It keeps no history; resuming after a reconnect is your job, driven by event ids. - **No status choice.** `StatusCode` is always `200`; there is no overload for another status. - **Null data still produces an event**, with an empty data field, so filter `null`s out of the sequence if the client cannot handle them. - **No buffering of the sequence.** Each item is formatted and written as soon as it is yielded. A controller action can return the same result, either typed as `ServerSentEventsResult<BuildProgress>` (which lets the endpoint pick up the result's metadata) or as `IResult`: ```csharp [HttpGet("/builds/{buildId}/progress")] public ServerSentEventsResult<BuildProgress> Progress(string buildId, CancellationToken ct) => TypedResults.ServerSentEvents(_store.WatchAsync(buildId, ct), eventType: "progress"); ``` ## Before .NET 10 Apps on .NET 8 or 9 still write the stream themselves: set the content type, disable buffering, write `data:` lines and flush after each event. Upgrading those endpoints to `TypedResults.ServerSentEvents` removes the hand-written formatting while keeping the same wire output.
- What happens if the iterator throws halfway through the build?The headers and earlier events have already been sent with status 200, so ASP.NET Core cannot turn the response into an error status or a ProblemDetails body. The exception ends the enumeration, the response is cut off, and the client sees the stream end and will normally try to reconnect. Report failures as a final event (for example an event type of `failed`) instead of throwing.
- Why might camelCase settings from AddControllers().AddJsonOptions not show up in an SSE event returned from a controller?`ServerSentEventsResult<T>` resolves `IOptions<Microsoft.AspNetCore.Http.Json.JsonOptions>`, the Minimal API JSON options, not MVC's `Microsoft.AspNetCore.Mvc.JsonOptions`. Settings made through `AddJsonOptions` therefore do not reach it. Configure the shared settings with `builder.Services.ConfigureHttpJsonOptions(...)` as well, or serialize to a string yourself and stream strings.
- TypedResults.ServerSentEvents only works in Minimal APIs, not in controllers.
- String items are JSON-encoded, so the client receives them in quotes.
- You still have to call Response.Body.FlushAsync after each yielded item.
- SSE events from a controller use MVC's AddJsonOptions settings.
- If the iterator fails, ASP.NET Core converts the response into a 500 ProblemDetails.
Assumes ASP.NET Core 10; TypedResults.ServerSentEvents and ServerSentEventsResult<T> are new in 10, and .NET 8 and 9 apps hand-write text/event-stream responses instead.