Without TypedResults.ServerSentEvents, how do you hand-write a Server-Sent Events response in ASP.NET Core, and what must each write do?
answer
- headers before the first byte
- text/event-stream and no-cache
- DisableBuffering on IHttpResponseBodyFeature
- WriteAsync flushes; StreamWriter does not
- loop on the request's CancellationToken
basics
~20 sSet ContentType to text/event-stream and Cache-Control to no-cache before writing, call DisableBuffering, then for each event write data: lines ending in a blank line and make sure the bytes are flushed, looping until the request's token is cancelled.
solid answer
~30 sThis is how .NET 8 and 9 apps stream SSE, and still how you emit things `SseFormatter` cannot, such as comment heartbeats. Before the first write, set `Response.ContentType = "text/event-stream"` and `Response.Headers.CacheControl = "no-cache"`, and call `context.Features.GetRequiredFeature<IHttpResponseBodyFeature>().DisableBuffering()`. Then, per build step, write `data: <json>` followed by a blank line. `HttpResponse.WriteAsync(string)` flushes the body writer itself, but a `StreamWriter` or serializer writing to `Response.Body` holds bytes until you call `FlushAsync`. Loop on the handler's `CancellationToken` (bound to `RequestAborted`), pass it to every await, and do not return until the stream is done, because returning completes the response.
code
csharp · 17 linesapp.MapGet("/builds/{buildId}/progress", async (string buildId, HttpContext context,
BuildStatusStore store, CancellationToken ct) =>
{
context.Response.ContentType = "text/event-stream"; // headers first
context.Response.Headers.CacheControl = "no-cache";
context.Features.GetRequiredFeature<IHttpResponseBodyFeature>().DisableBuffering();
while (!ct.IsCancellationRequested)
{
var progress = await store.GetProgressAsync(buildId, ct);
var json = JsonSerializer.Serialize(progress, JsonSerializerOptions.Web);
await context.Response.WriteAsync($"event: progress\ndata: {json}\n\n", ct); // flushes
if (progress.PercentComplete == 100) break;
await Task.Delay(TimeSpan.FromSeconds(1), ct);
}
});go deeper
Remember the recipe: text/event-stream and no-cache headers first, then data lines ending with a blank line, written in a loop.
Explain which write APIs flush on their own, why headers must precede the first write, and how the CancellationToken parameter ends the loop.
Know where DisableBuffering matters (IIS, compression) versus Kestrel, and when a hand-written stream is still needed in .NET 10.
Plan the migration of hand-written streams to the .NET 10 result type and decide which endpoints justify keeping custom output.
## When you still write the stream yourself ASP.NET Core 10's `TypedResults.ServerSentEvents` formats events for you. You still hand-write the response when: - the app targets **.NET 8 or .NET 9**, which have no SSE result type; - you need output `SseFormatter` never produces, such as **comment lines** used as idle heartbeats (it always writes a `data:` line per event); - you are adapting an existing writer, for example a library that writes to a `Stream`. The steps are the same in a Minimal API handler, a controller action or middleware. ## Step 1: headers, before anything is written The status line and headers leave the server with the first body bytes. After that, setting a header throws or is ignored. So, first: 1. `context.Response.ContentType = "text/event-stream";` 2. `context.Response.Headers.CacheControl = "no-cache";` so no cache stores the stream. 3. Optionally `context.Response.Headers.ContentEncoding = "identity";` so the response compression middleware skips the response, which is what the built-in result does. ## Step 2: disable buffering `context.Features.GetRequiredFeature<IHttpResponseBodyFeature>().DisableBuffering();` On Kestrel this call does nothing, because Kestrel does not hold response bytes back once they are flushed. It matters elsewhere: IIS in-process turns off its native response buffering and dynamic compression, and the response compression middleware switches to flushing on every write or stops compressing. Calling it is cheap and makes the handler correct on any host. ## Step 3: write each event, and make sure it leaves One event is one or more `data:` lines followed by an empty line. For a JSON payload on a single line: - `await context.Response.WriteAsync($"data: {json}\n\n", ct);` Whether the bytes reach the client immediately depends on **how** you write: | Write method | Flushes on its own? | |---|---| | `HttpResponse.WriteAsync(string)` | yes: it ends by flushing `BodyWriter` | | `context.Response.BodyWriter.WriteAsync(...)` | yes: `PipeWriter.WriteAsync` writes and flushes | | a `StreamWriter` over `Response.Body` | no: text waits in its buffer until `FlushAsync` | Serialize with web-style settings (`JsonSerializerOptions.Web`) if the dashboard expects camelCase, since a bare `JsonSerializer.Serialize` call uses the default PascalCase settings. ## Step 4: stay in the loop until done The handler's `Task` is the response. Loop while the build is running, pass the `CancellationToken` parameter (bound to `HttpContext.RequestAborted` in Minimal APIs) to every await, and return only when the build finishes or the client leaves. A disconnect then surfaces as an `OperationCanceledException`, which is expected and should not be logged as an error. ## The same code in a controller Nothing is specific to Minimal APIs. An MVC action declared `public async Task Progress(string buildId, CancellationToken ct)` sets `Response.ContentType`, calls `DisableBuffering` through `HttpContext.Features`, writes in a loop and returns when the build is done; MVC binds `ct` to the request-aborted token as well. The action must not return a result object after writing, because the response has already started. ## Mistakes that break a hand-written stream | Mistake | What the client sees | |---|---| | header set after the first write | wrong content type; the browser's event source refuses the stream | | event written without the blank line | it merges with the next event, and nothing is dispatched until a blank line ends the block | | `StreamWriter` never flushed | events arrive in bursts, or at the end | | loop moved into `Task.Run` and handler returns | the stream ends at once; later writes fail | | no token passed to the wait for the next event | abandoned streams keep running server-side | ## Moving to .NET 10 When the app upgrades, the loop usually becomes an `IAsyncEnumerable<T>` returned through `TypedResults.ServerSentEvents`. Keep the hand-written version only where you need output the formatter cannot produce.
- How would you send an idle heartbeat from a hand-written stream?Write a comment line, a line starting with a colon followed by a blank line, every so often when no build event has been sent, for example from a `Task.WhenAny` between the next event and a timer. Clients ignore comments, but the bytes keep idle proxies from closing the connection. `TypedResults.ServerSentEvents` cannot emit comments, which is one reason to keep a hand-written stream in .NET 10.
- Why set the headers before calling DisableBuffering and writing?Order matters only relative to the first write: headers are sent with the first body bytes, and the response compression middleware's body wrapper documents that `DisableBuffering` is only effective before the first write. Doing all three at the top of the handler, before any await that might write, avoids both traps.
- Set Response.ContentType after the first event; ASP.NET Core sends headers at the end.
- Kestrel buffers the whole response, so DisableBuffering is what makes SSE work there.
- A StreamWriter over Response.Body sends each line immediately.
- Return from the handler and keep writing to Response.Body from a background task.
- TypedResults.ServerSentEvents can emit comment lines for heartbeats.
Assumes ASP.NET Core 10, where TypedResults.ServerSentEvents exists; on ASP.NET Core 8 and 9 this hand-written stream is the only built-in way to serve Server-Sent Events.