AI-powered applications often need to generate long responses. For example, a chatbot may explain a programming concept, summarize a document, or analyze a large amount of information. When an application waits for the complete AI response before displaying anything, users may experience unnecessary delays.
Streaming provides a better experience. Instead of waiting for the entire response, the application sends generated content to the client as it becomes available. Users can start reading the answer while the model continues generating the remaining content.
ASP.NET Core supports streaming HTTP responses, while Microsoft.Extensions.AI provides a common abstraction for communicating with different AI models. By combining these capabilities, developers can build AI-powered APIs that stream responses without tightly coupling application code to a specific model provider.
In this article, we will build a streaming AI endpoint using ASP.NET Core, Microsoft.Extensions.AI, and Ollama. We will explore how to configure the AI client, stream response updates, implement Server-Sent Events (SSE), handle cancellation, consume the stream from a browser, and manage common production issues.
Why Use Streaming Responses in an ASP.NET Core Application?
Consider a traditional AI API endpoint.
A client sends a question, the ASP.NET Core application forwards it to the AI model, and the model generates a complete response. Only after generation finishes does the API return the result.
The request flow looks like this:
Browser or Mobile App
|
v
ASP.NET Core API
|
v
AI Model
|
v
Generate Complete Response
|
v
Return HTTP ResponseThis approach is simple, but it has a limitation. The client receives no useful response content while the model is generating its answer.
With streaming, the model sends response updates incrementally.
Browser or Mobile App
|
v
ASP.NET Core API
|
v
AI Model
|
v
Response Update 1
|
v
Response Update 2
|
v
Response Update 3
|
v
Response CompleteThe application forwards each update to the client as it arrives.
Streaming is particularly useful for:
AI chat applications.
Developer assistants.
Document summarization tools.
AI-powered customer support.
Applications that generate long responses.
Interactive applications where users expect immediate feedback.
Streaming does not necessarily make the model generate answers faster. It improves the user experience by reducing the time users wait before seeing the first part of the response.
Understanding Microsoft.Extensions.AI Streaming
Microsoft.Extensions.AI provides the IChatClient interface for communicating with AI services.
It supports two common response methods:
Method | Description |
|---|---|
GetResponseAsync | Returns the complete AI response |
GetStreamingResponseAsync | Returns response updates incrementally |
The GetResponseAsync method returns a ChatResponse after the model finishes generating the answer.
In contrast, GetStreamingResponseAsync returns an IAsyncEnumerable of ChatResponseUpdate objects.
This allows developers to process each update using C# asynchronous iteration.
The important advantage is that application code can use the same abstraction with different AI providers, provided they supply compatible IChatClient implementations.
Preparing the ASP.NET Core Project
We will use Ollama as the local AI runtime for this example.
First, install Ollama and download a model:
ollama pull llama3.2Start the Ollama service and verify that the model is available:
ollama listNext, create an ASP.NET Core Minimal API project:
dotnet new web -n StreamingAIApp
cd StreamingAIAppInstall the required NuGet packages:
dotnet add package Microsoft.Extensions.AI
dotnet add package OllamaSharpThe Microsoft.Extensions.AI package provides the IChatClient abstraction, while OllamaSharp provides the implementation required to communicate with Ollama.
The application will expose an HTTP endpoint that accepts a user's question and streams the generated response.
Configuring the AI Client
Open Program.cs and configure the AI client using dependency injection.
using Microsoft.Extensions.AI;
using OllamaSharp;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IChatClient>(
_ => new OllamaApiClient(
new Uri("http://localhost:11434"),
"llama3.2"
)
);
var app = builder.Build();
app.Run();The application registers an Ollama client as an IChatClient service.
This allows ASP.NET Core to inject the AI client into endpoint handlers.
Using IChatClient instead of directly depending on OllamaApiClient makes the application easier to maintain. You can replace the underlying provider later without changing the streaming endpoint's core logic.
For production applications, move the endpoint and model name into configuration rather than hardcoding them.
Creating a Streaming API Endpoint
Now, let's create an endpoint that accepts a question and streams the AI response.
We will use Server-Sent Events (SSE) to send incremental updates to the client.
SSE is an HTTP-based mechanism that allows a server to send events to a client over a long-lived response connection.
Each event contains a data field followed by a blank line.
For example:
data: "Hello"
data: " from"
data: " ASP.NET Core"
In this example, each event contains a JSON-encoded string.
Add the following code to Program.cs:
using System.Text.Json;
using Microsoft.Extensions.AI;
using OllamaSharp;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IChatClient>(
_ => new OllamaApiClient(
new Uri("http://localhost:11434"),
"llama3.2"
)
);
var app = builder.Build();
app.MapPost(
"/api/chat/stream",
async (
ChatRequest request,
IChatClient chatClient,
HttpContext context) =>
{
if (string.IsNullOrWhiteSpace(request.Message))
{
return Results.BadRequest(
new { error = "Message is required." }
);
}
context.Response.ContentType =
"text/event-stream";
context.Response.Headers.CacheControl =
"no-cache";
context.Response.Headers["X-Accel-Buffering"] =
"no";
try
{
await foreach (
ChatResponseUpdate update in
chatClient.GetStreamingResponseAsync(
request.Message,
cancellationToken: context.RequestAborted))
{
if (string.IsNullOrEmpty(update.Text))
continue;
string eventData =
JsonSerializer.Serialize(update.Text);
await context.Response.WriteAsync(
$"data: {eventData}\n\n",
context.RequestAborted
);
await context.Response.Body.FlushAsync(
context.RequestAborted
);
}
await context.Response.WriteAsync(
"event: done\ndata: {}\n\n",
context.RequestAborted
);
await context.Response.Body.FlushAsync(
context.RequestAborted
);
}
catch (OperationCanceledException)
when (context.RequestAborted.IsCancellationRequested)
{
app.Logger.LogInformation(
"AI streaming request was cancelled."
);
}
catch (Exception ex)
{
app.Logger.LogError(
ex,
"AI streaming request failed."
);
if (!context.RequestAborted.IsCancellationRequested)
{
if (context.Response.HasStarted)
{
await context.Response.WriteAsync(
"event: error\ndata: " +
"{\"message\":\"AI generation failed.\"}\n\n"
);
await context.Response.Body.FlushAsync();
}
else
{
throw;
}
}
}
}
);
app.Run();
public sealed record ChatRequest(string Message);Let's understand the important parts of this implementation.
Accepting the User's Question
The endpoint accepts a ChatRequest object containing the user's message.
public sealed record ChatRequest(string Message);ASP.NET Core automatically binds the incoming JSON request to this record.
For example, a client can send:
{
"message": "Explain dependency injection in C#."
}The endpoint validates the message before calling the AI model.
Setting the SSE Response Headers
context.Response.ContentType = "text/event-stream";This tells the client that the response uses the Server-Sent Events format.
The Cache-Control header prevents caching of the streaming response.
The X-Accel-Buffering header is useful when running behind Nginx because it requests that response buffering be disabled for this endpoint. Other reverse proxies may require their own buffering configuration.
Calling GetStreamingResponseAsync
await foreach (
ChatResponseUpdate update in
chatClient.GetStreamingResponseAsync(
request.Message,
cancellationToken: context.RequestAborted))This is the central part of the implementation.
GetStreamingResponseAsync returns an asynchronous sequence of response updates.
The await foreach statement processes each update as it becomes available.
The application does not need to wait for the complete response before sending content to the client.
Writing Each Update to the HTTP Response
string eventData =
JsonSerializer.Serialize(update.Text);
await context.Response.WriteAsync(
$"data: {eventData}\n\n",
context.RequestAborted
);Each update is serialized as JSON and written using the SSE data format.
Serializing the text is important because response content may contain newline characters, quotation marks, or other characters that need proper escaping.
Join the conversation! Your thoughts help the community grow.