skip to content

Raw Push Channels

Pushing data to clients from ASP.NET Core without SignalR: raw WebSocket endpoints and Server-Sent Events results. Interviewers ask when these beat SignalR and what holding a request open costs.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

11

In ASP.NET Core 10, how do you stream Server-Sent Events with TypedResults.ServerSentEvents, and what does the result set up for you?

level: juniorimportance: must knowfreq 50%

answer

  1. new result type in .NET 10
  2. IAsyncEnumerable<T> in, events out
  3. ServerSentEventsResult<T>
  4. headers plus DisableBuffering
  5. JSON via Http.Json JsonOptions

basics

~10 s

Return 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 s

ASP.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 lines
csharp
app.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

for a junior

Know that ASP.NET Core 10 streams SSE with TypedResults.ServerSentEvents over an IAsyncEnumerable and that each yielded item becomes one event.

for a middle

Walk through what ServerSentEventsResult<T> does: the headers it sets, DisableBuffering, JSON with the Http.Json options and raw strings.

for a senior

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.

for a principal

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.

open as a page

In ASP.NET Core 10, how do you accept a raw WebSocket without SignalR, and why must the handler stay running until it closes?

level: juniorimportance: must knowfreq 58%

basics

~10 s

Call app.UseWebSockets(), then in the endpoint check context.WebSockets.IsWebSocketRequest and await AcceptWebSocketAsync() to get a WebSocket. The handler must await its receive/send loop, because returning ends the request and tears the socket down.

open as a page

In an ASP.NET Core raw WebSocket handler, how should the receive loop assemble messages and finish the close handshake cleanly?

level: middleimportance: must knowfreq 50%

basics

~10 s

Loop on ReceiveAsync into a buffer, appending Count bytes until EndOfMessage, then handle the message. When MessageType is Close, answer with CloseAsync and exit; an abrupt disconnect surfaces as a WebSocketException to catch.

open as a page

Without TypedResults.ServerSentEvents, how do you hand-write a Server-Sent Events response in ASP.NET Core, and what must each write do?

level: middleimportance: should knowfreq 30%

basics

~20 s

Set 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.

open as a page

With ASP.NET Core 10's TypedResults.ServerSentEvents, how do SseItem<T> event types and ids let a build dashboard resume after a reconnect?

level: middleimportance: should knowfreq 38%

basics

~20 s

Yield 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.

open as a page

In ASP.NET Core 10's WebSocketOptions, what do KeepAliveInterval and KeepAliveTimeout default to, and how does KeepAliveTimeout change dead-client detection?

level: middleimportance: should knowfreq 36%

basics

~10 s

KeepAliveInterval defaults to two minutes and KeepAliveTimeout to Timeout.InfiniteTimeSpan (off). With only the interval, the server sends one-way heartbeats; setting KeepAliveTimeout makes it ping and abort the socket if no pong arrives in time.

open as a page

In ASP.NET Core, what does IHttpResponseBodyFeature.DisableBuffering change for a Server-Sent Events stream on Kestrel, on IIS and under response compression?

level: seniorimportance: should knowfreq 28%

basics

~20 s

On Kestrel nothing: its DisableBuffering is empty. On IIS in-process it turns off native response buffering and dynamic compression. Under the response compression middleware it makes compression flush every write, or skips it; Content-Encoding: identity skips compression entirely.

open as a page

When a dashboard tab closes, how does an ASP.NET Core 10 SSE endpoint stop its IAsyncEnumerable, and why might the iterator keep running anyway?

level: seniorimportance: should knowfreq 33%

basics

~20 s

ServerSentEventsResult passes RequestAborted to SseFormatter, which cancels its writes. Your iterator only stops waiting if the token reaches it: pass the handler's CancellationToken in explicitly, because the plain-T and string overloads enumerate your sequence without a token.

open as a page

In ASP.NET Core without SignalR, how would you push each new auction bid to thousands of open raw WebSockets safely?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Register each connection with its own bounded Channel and one writer loop calling SendAsync. The broadcaster TryWrites into every channel without awaiting sockets; each handler awaits its loops and deregisters when the socket closes or faults.

open as a page

Your ASP.NET Core raw WebSocket endpoint for auction bids trusts the site's auth cookie; why does CORS not protect it, and what does WebSocketOptions.AllowedOrigins enforce?

level: seniorimportance: should knowfreq 34%

basics

~20 s

Browsers skip CORS for WebSocket handshakes, so any site can open a socket carrying the user's cookie. With entries, AllowedOrigins makes the middleware answer 403 to unlisted origins; empty (the default) allows all, and requests without Origin pass.

open as a page

Why might an ASP.NET Core raw WebSocket endpoint mapped with MapGet or [HttpGet] fail for browsers over HTTPS, and what fixes it?

level: seniorimportance: nice to knowfreq 18%

basics

~20 s

Over HTTPS, Kestrel negotiates HTTP/2, where a browser opens a WebSocket with an extended CONNECT request, not a GET. A GET-only route never matches it; map the endpoint with app.Map or [Route] so any method reaches it.

open as a page