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?

The server validates the POST before sending SSE. The client renders deltas and treats done or error as a terminal event.
The server validates the POST before sending SSE. The client renders deltas and treats done or error as a terminal event.
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.

Lab.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup><TargetFramework>net10.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable></PropertyGroup>
</Project>
Program.cs
using System.Net.ServerSentEvents;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Runtime.CompilerServices;

var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(k => k.Limits.MaxRequestBodySize = 8192);
builder.Services.AddHttpClient("openai", c =>
{
    c.BaseAddress = new Uri("https://api.openai.com/");
    c.Timeout = Timeout.InfiniteTimeSpan; // The entire stream has an explicit budget below.
});
var app = builder.Build();
app.Use(async (ctx, next) =>
{
    if (ctx.Request.Host.Host != "127.0.0.1" || ctx.Request.Headers.ContainsKey("Origin"))
    { ctx.Response.StatusCode = 403; return; }
    await next(ctx);
});
app.MapPost("/chat/stream", (Prompt body, HttpContext ctx, IHttpClientFactory clients, IConfiguration config) =>
{
    if (string.IsNullOrWhiteSpace(body.Text) || body.Text.Length > 1000)
        return (IResult)Results.BadRequest("Use 1–1000 characters.");
    ctx.Response.Headers.CacheControl = "no-store";
    ctx.Response.Headers["X-Accel-Buffering"] = "no";
    var key = config["OpenAI:ApiKey"];
    var model = config["OpenAI:Model"];
    if (key is null || model is null)
        return TypedResults.ServerSentEvents(Stream(body.Fail, ctx.RequestAborted));
    return TypedResults.ServerSentEvents(ProviderStream(clients, key, model, body.Text,
        ctx.RequestAborted));
});
await app.RunAsync();

static async IAsyncEnumerable<SseItem<string>> Stream(
    bool fail, [EnumeratorCancellation] CancellationToken ct)
{
    foreach (var text in new[] { "Here ", "is a ", "sample reply." })
    {
        await Task.Delay(250, ct);
        yield return new SseItem<string>(text, "delta");
        if (fail)
        {
            yield return new SseItem<string>("The provider did not finish.", "error");
            yield break;
        }
    }

    yield return new SseItem<string>("complete", "done");
}
static async IAsyncEnumerable<SseItem<string>> ProviderStream(
    IHttpClientFactory clients, string key, string model, string prompt,
    [EnumeratorCancellation] CancellationToken requestAborted)
{
    using var budget = CancellationTokenSource.CreateLinkedTokenSource(requestAborted);
    budget.CancelAfter(TimeSpan.FromSeconds(45));
    using var client = clients.CreateClient("openai");
    using var request = new HttpRequestMessage(HttpMethod.Post, "v1/responses")
    {
        Content = JsonContent.Create(new
        {
            model, input = prompt, stream = true, store = false, max_output_tokens = 500
        })
    };
    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", key);
    using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead,
        budget.Token);
    if (!response.IsSuccessStatusCode ||
        response.Content.Headers.ContentType?.MediaType != "text/event-stream")
    {
        yield return new SseItem<string>("Provider did not start a stream.", "error");
        yield break;
    }

    await using var stream = await response.Content.ReadAsStreamAsync(budget.Token);
    await foreach (var item in SseParser.Create(stream).EnumerateAsync(budget.Token))
    {
        if (item.EventType == "response.output_text.delta")
        {
            using var json = JsonDocument.Parse(item.Data);
            if (json.RootElement.TryGetProperty("delta", out var delta) &&
                delta.ValueKind == JsonValueKind.String)
                yield return new SseItem<string>(delta.GetString()!, "delta");
        }
        else if (item.EventType == "response.completed")
        {
            yield return new SseItem<string>("complete", "done");
            yield break;
        }
        else if (item.EventType is "response.failed" or "response.incomplete" or "error")
        {
            yield return new SseItem<string>("Provider did not finish.", "error");
            yield break;
        }
    }

    yield return new SseItem<string>("Stream ended without a completion event.", "error");
}

record Prompt(string Text, bool Fail = false);

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

client.py
import json
from urllib.request import Request, urlopen

request = Request(
    "http://127.0.0.1:5080/chat/stream",
    data=json.dumps({"text": "Hello", "fail": False}).encode(),
    headers={"Content-Type": "application/json", "Accept": "text/event-stream"},
)
finished = False
with urlopen(request, timeout=10) as response:
    if response.headers.get_content_type() != "text/event-stream":
        raise RuntimeError("Unexpected content type")
    event, data = "message", []
    for raw in response:
        line = raw.decode("utf-8").rstrip("\r\n")
        if not line:
            if data:
                payload = "\n".join(data)
                if event == "delta":
                    print(payload, end="", flush=True)
                elif event == "error":
                    raise RuntimeError(payload)
                elif event == "done":
                    finished = True
                    break
            event, data = "message", []
        elif not line.startswith(":"):
            field, _, value = line.partition(":")
            value = value[1:] if value.startswith(" ") else value
            if field == "event":
                event = value
            elif field == "data":
                data.append(value)
if not finished:
    raise RuntimeError("Stream ended before completion")
print()

Run the host in one terminal and the test in another.

Run the deterministic fixture
dotnet run --no-launch-profile -- --urls http://127.0.0.1:5080
python3 client.py

The expected output is Here is a sample reply.. To inspect event framing and a known failure use curl without response buffering.

Inspect a terminal error after a delta
curl -NsS http://127.0.0.1:5080/chat/stream \
  -H 'Content-Type: application/json' -H 'Accept: text/event-stream' \
  -d '{"text":"Hello","fail":true}'

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.

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