How to Stream AI Chat Responses in ASP.NET Core 10 Using Server-Sent Events and C# (2026)
A chat stream should tell the client when to render text and when the result is final. Treating an ordinary socket close as success can leave an incomplete reply on screen with no indication that anything failed.
This tutorial builds an ASP.NET Core 10 server-sent events endpoint for AI chat. It supports a deterministic local fixture and an optional OpenAI streaming adapter. The API accepts a POST, forwards incremental text deltas, and defines distinct terminal done and error events.
What should the SSE contract contain?
| Event | Meaning | Client behavior |
|---|---|---|
| delta | More answer text | Append as text |
| done | Provider completed | Mark reply complete |
| error | Known terminal failure | Show safe error and keep prior text marked partial |
| EOF without terminal event | Transport or application stopped unexpectedly | Treat reply as interrupted |
SSE is a UTF-8 text format. A blank line ends one event and multiple data lines join with a newline. Network reads do not necessarily align with lines or events. Use a proper parser. The browser’s native EventSource uses GET, so a POST with JSON input uses a streaming fetch implementation or a compatible client. The included Python reader keeps the protocol test independent of browser CORS. See the HTML event stream specification and ASP.NET Core SSE API.
Build the SSE server
Install .NET 10 and Python 3 for the small terminal client. The server needs no additional NuGet package. Create the files below in a new directory. Run locally with the loopback binding. The sample rejects browser Origin and unexpected Host headers and deliberately has no remote authentication. Require authorization, rate limiting and an appropriate Origin/CORS policy for public use.
The built-in formatter sends an async sequence of typed events. The fixture emits three text deltas or a deliberate error after the first. With both OpenAI settings present, the server uses ResponseHeadersRead to start parsing without buffering the full upstream response. It maps provider events to a smaller application contract and applies a hard 45-second deadline linked to the client disconnect. Only a provider completion event maps to done. See OpenAI streaming Responses.
The status and headers may already be sent before a provider or parser fails. The adapter uses an error event for recognized terminal conditions. An unexpected I/O or parse exception may close the stream without a terminal event. The client treats that as interruption. Production code can add a dedicated adapter layer that translates additional safe error categories before they escape, while preserving request-abort cancellation.
Create the client and test the stream
Run the host in one terminal and the test in another.
The expected output is Here is a sample reply.. To inspect event framing and a known failure use curl without response buffering.
For the live model path, set OpenAI__ApiKey and OpenAI__Model in the server process. Choose a Responses-compatible model with streaming access. The provider reply text will vary. Verify that the public client never receives the credential or provider error details. Close the client midstream and confirm the server stops enumerating. A client-side interruption alone does not prove that an upstream dependency stopped or that billing ceased.
The server compiled on .NET SDK 10.0.100. The deterministic loopback stream completed in the Python client, and the forced failure emitted a delta followed by an error event. The live provider and production proxy were not exercised.
Diagnose buffering and production disconnects
If output arrives all at once, test directly against Kestrel before testing ingress. Inspect the response content type and per-event timing. Proxy buffering, response compression, a middleware that records the full body, and client stdout buffering can all hide useful evidence. X-Accel-Buffering: no is a hint for compatible proxies, and the actual behavior must be verified through the deployed stack.
Use an idle timeout and a total deadline appropriate for the provider. Heartbeat comments can keep a proxy connection active during expected idle gaps, but do not extend the work deadline indefinitely. A slow consumer can hold an upstream connection. Bound concurrent streams per user, avoid unbounded intermediate queues, and await the next write.
Do not automatically retry a paid generation after partial output. A retry can create a second provider call and produce different text. Durable resumption requires a separate event log and sequence semantics. This sample gives partial output a distinct UI state. If you later persist replies, save only after a terminal success or mark partial results explicitly.
| Symptom | Check |
|---|---|
| 400 before streaming | Request size and input |
| Browser EventSource cannot POST | Use streaming fetch or a different initiation protocol |
| Text appears in one burst | Proxy and client buffering |
| EOF with no done | Disconnect, upstream deadline or stream parser failure |
| Retry repeats paid work | Stable request ID and durable deduplication |
FAQ and references
Why use SSE instead of WebSockets? SSE works well when the app sends a request and the server streams one-way text. Use a bidirectional transport when the interaction genuinely needs both sides to send ongoing messages.
Should I render chunks as HTML? Append as text or sanitize the final rendered Markdown. Partial model output is still untrusted input.
Can a stream change from HTTP 200 to HTTP 502? Once headers are sent, express the failure through the stream contract or connection termination.
- ASP.NET PB OpenAI API integration.
- ASP.NET PB MCP progress and cancellation.
- .NET cooperative cancellation.
Give the stream a clear terminal contract and test it through the real proxy. A client that can distinguish completion from interruption can recover without silently presenting a partial answer as final.
Comments
Post a Comment