Skip to main content

Build a Streaming Chat API with Azure OpenAI + ASP.NET Core Minimal API

Verified Nov 2026 From NuGet Release .NET 10 Azure.AI.OpenAI 2.1.0
By Rajesh Mishra · Published: · Updated: · 18 min read
Diagram showing a browser connected to an ASP.NET Core server-sent events endpoint that streams tokens from Azure OpenAI
Streaming reduces time-to-first-token by sending partial model output through SSE as soon as it is available.
In 30 Seconds

Build a .NET 10 Minimal API with Azure OpenAI, in-memory conversation history, and three response formats. The browser example reads a POST SSE response with fetch and buffers partial frames so network chunk boundaries cannot split or discard text.

What You'll Build

Build an ASP.NET Core streaming chat API with Azure OpenAI and .NET 10. Send text over SSE and handle split events in a browser using fetch.

Streaming changes the dynamics of a chat API. Instead of waiting several seconds for a complete response, users see tokens arrive in real time. The experience goes from sluggish to conversational. This workshop builds that experience from scratch, covering project setup, dependency injection, retry logic, three distinct endpoint patterns, error handling, and conversation history — all in a single runnable .NET 10 project.

By the end, you will have a local API that serves non-streaming JSON, streaming IAsyncEnumerable, and Server-Sent Events to browser clients. The browser example preserves newlines and Unicode even when an event arrives in pieces.

Prerequisites

Before you begin, make sure you have the following ready:

  • .NET 10 SDK installed
  • An Azure subscription with an Azure OpenAI resource provisioned
  • A deployed chat model (for example GPT-5 or GPT-5 mini)
  • Your Azure OpenAI endpoint and API key (or a configured managed identity)

If Azure returns a 404 during setup, check which endpoint and deployment name your application is using before debugging the streaming code.

Step 1 — Scaffold the Project

Create a new Minimal API project and move into the directory:

dotnet new webapi -n StreamingChatApi --use-minimal-apis
cd StreamingChatApi

Install the Azure OpenAI SDK from NuGet:

dotnet add package Azure.AI.OpenAI --version 2.1.0

This pulls in the OpenAI base package as a transitive dependency. You do not need to install it separately.

Step 2 — Configure Application Settings

Set the endpoint and deployment in appsettings.json. Supply the key through local user secrets with dotnet user-secrets init and dotnet user-secrets set "AzureOpenAI:ApiKey" "<your-key>".

{
  "AzureOpenAI": {
    "Endpoint": "https://<your-resource>.openai.azure.com/",
    "DeploymentName": "chat-deployment"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information"
    }
  }
}

For production, store the API key in Azure Key Vault or use DefaultAzureCredential with managed identity. Never commit secrets to source control.

Step 3 — Define the Configuration and Request Models

Create a Models folder and add the following files.

Models/AzureOpenAISettings.cs

namespace StreamingChatApi.Models;

public sealed class AzureOpenAISettings
{
    public const string SectionName = "AzureOpenAI";

    public required string Endpoint { get; init; }
    public required string ApiKey { get; init; }
    public required string DeploymentName { get; init; }
}

Models/ChatRequest.cs

namespace StreamingChatApi.Models;

public sealed class ChatRequest
{
    public required string Message { get; init; }
    public string? ConversationId { get; init; }
}

Models/ChatResponse.cs

namespace StreamingChatApi.Models;

public sealed class ChatResponse
{
    public required string Message { get; init; }
    public required string ConversationId { get; init; }
    public int PromptTokens { get; init; }
    public int CompletionTokens { get; init; }
}

Step 4 — Register the Azure OpenAI Client with Retry Logic

The AzureOpenAIClient is thread-safe and should be registered as a singleton. Wrapping it with a retry policy ensures transient failures — especially 429 rate-limit responses — are handled automatically.

If you’re migrating from Azure.AI.OpenAI v1, see Azure OpenAI SDK v2 Migration Guide for C# for the complete breaking changes reference.

Open Program.cs and configure dependency injection:

using System.ClientModel;
using System.ClientModel.Primitives;
using System.Text.Json;
using Azure;
using Azure.AI.OpenAI;
using StreamingChatApi.Models;
using StreamingChatApi.Services;

var builder = WebApplication.CreateBuilder(args);

// Bind configuration
builder.Services.Configure<AzureOpenAISettings>(
    builder.Configuration.GetSection(AzureOpenAISettings.SectionName));

// Register AzureOpenAIClient as singleton with retry
builder.Services.AddSingleton(sp =>
{
    var settings = builder.Configuration
        .GetSection(AzureOpenAISettings.SectionName)
        .Get<AzureOpenAISettings>()
        ?? throw new InvalidOperationException("AzureOpenAI settings are missing.");

    var clientOptions = new AzureOpenAIClientOptions
    {
        RetryPolicy = new ClientRetryPolicy(maxRetries: 3)
    };

    return new AzureOpenAIClient(
        new Uri(settings.Endpoint),
        new AzureKeyCredential(settings.ApiKey),
        clientOptions);
});

// Register application services
builder.Services.AddSingleton<ConversationStore>();
builder.Services.AddScoped<ChatService>();

var app = builder.Build();

The ClientRetryPolicy ships with the System.ClientModel library. It retries on 429 and 5xx status codes with exponential back-off, respecting Retry-After headers from Azure. Three retries covers most transient spikes.

Step 5 — Build the Conversation Store

Multi-turn chat requires history. A production system would persist conversations in a database. For this workshop, an in-memory concurrent dictionary does the job.

Services/ConversationStore.cs

using System.Collections.Concurrent;
using OpenAI.Chat;

namespace StreamingChatApi.Services;

public sealed class ConversationStore
{
    private readonly ConcurrentDictionary<string, List<ChatMessage>> _conversations = new();

    public string CreateConversation()
    {
        var id = Guid.NewGuid().ToString("N");
        _conversations[id] = new List<ChatMessage>
        {
            new SystemChatMessage(
                "You are a helpful assistant. Be concise and accurate.")
        };
        return id;
    }

    private List<ChatMessage> GetMessages(string conversationId)
    {
        if (!_conversations.TryGetValue(conversationId, out var messages))
            throw new KeyNotFoundException(
                $"Conversation '{conversationId}' not found.");
        return messages;
    }

    public ChatMessage[] AddUserMessageAndSnapshot(string conversationId, string content)
    {
        var messages = GetMessages(conversationId);
        lock (messages)
        {
            messages.Add(new UserChatMessage(content));
            return messages.ToArray();
        }
    }

    public void AddAssistantMessage(string conversationId, string content)
    {
        var messages = GetMessages(conversationId);
        lock (messages)
        {
            messages.Add(new AssistantChatMessage(content));
        }
    }
}

The lock lets each request capture a stable snapshot of the messages it sends upstream. Serialize turns for the same conversation in a multi-user app so overlapping requests cannot produce out-of-order replies. Authenticate access to conversation IDs and cap the retained history.

Step 6 — Implement the Chat Service

The ChatService wraps the Azure OpenAI SDK and exposes both non-streaming and streaming methods. Under sustained load, streaming endpoints are still subject to Azure OpenAI rate limits — see Fix Azure OpenAI 429 Too Many Requests in .NET for retry policies and circuit breaker configuration.

Services/ChatService.cs

using System.Runtime.CompilerServices;
using Azure.AI.OpenAI;
using Microsoft.Extensions.Options;
using OpenAI.Chat;
using StreamingChatApi.Models;

namespace StreamingChatApi.Services;

public sealed class ChatService
{
    private readonly AzureOpenAIClient _aiClient;
    private readonly ConversationStore _store;
    private readonly AzureOpenAISettings _settings;

    public ChatService(
        AzureOpenAIClient aiClient,
        ConversationStore store,
        IOptions<AzureOpenAISettings> settings)
    {
        _aiClient = aiClient;
        _store = store;
        _settings = settings.Value;
    }

    public async Task<ChatResponse> CompleteAsync(ChatRequest request)
    {
        var conversationId = request.ConversationId
            ?? _store.CreateConversation();
        var messages = _store.AddUserMessageAndSnapshot(conversationId, request.Message);

        var chatClient = _aiClient.GetChatClient(_settings.DeploymentName);
        ChatCompletion completion = await chatClient.CompleteChatAsync(messages);

        var reply = completion.Content[0].Text;
        _store.AddAssistantMessage(conversationId, reply);

        return new ChatResponse
        {
            Message = reply,
            ConversationId = conversationId,
            PromptTokens = completion.Usage.InputTokenCount,
            CompletionTokens = completion.Usage.OutputTokenCount
        };
    }

    public async IAsyncEnumerable<string> StreamAsync(
        ChatRequest request,
        [EnumeratorCancellation] CancellationToken cancellationToken = default)
    {
        var conversationId = request.ConversationId
            ?? _store.CreateConversation();
        var messages = _store.AddUserMessageAndSnapshot(conversationId, request.Message);

        var chatClient = _aiClient.GetChatClient(_settings.DeploymentName);
        var fullResponse = new System.Text.StringBuilder();

        await foreach (StreamingChatCompletionUpdate update in
            chatClient.CompleteChatStreamingAsync(messages, cancellationToken: cancellationToken))
        {
            foreach (ChatMessageContentPart part in update.ContentUpdate)
            {
                if (part.Text is { Length: > 0 } text)
                {
                    fullResponse.Append(text);
                    yield return text;
                }
            }
        }

        _store.AddAssistantMessage(conversationId, fullResponse.ToString());
    }
}

Two critical design decisions live here. First, CompleteAsync returns the entire response in one shot, which is simpler when latency is not the primary concern. Second, StreamAsync returns IAsyncEnumerable<string>, yielding individual token fragments as they arrive. The StringBuilder accumulates the full response so conversation history stays complete.

Step 7 — Wire Up the Endpoints

Add three endpoints to Program.cs after the var app = builder.Build(); line:

// Non-streaming endpoint
app.MapPost("/api/chat", async (ChatRequest request, ChatService chat) =>
{
    try
    {
        var response = await chat.CompleteAsync(request);
        return Results.Ok(response);
    }
    catch (ClientResultException ex) when (ex.Status == 401)
    {
        return Results.Problem(
            "Authentication failed. Check your API key.",
            statusCode: 401);
    }
    catch (ClientResultException ex) when (ex.Status == 429)
    {
        return Results.Problem(
            "Rate limit exceeded. Try again later.",
            statusCode: 429);
    }
});

// Streaming endpoint returning IAsyncEnumerable
app.MapPost("/api/chat/stream",
    (ChatRequest request, ChatService chat, HttpContext context) =>
        Results.Ok(chat.StreamAsync(request, context.RequestAborted)));

// SSE endpoint for browser clients
app.MapPost("/api/chat/sse", async (
    ChatRequest request,
    ChatService chat,
    HttpContext context) =>
{
    context.Response.ContentType = "text/event-stream";
    context.Response.Headers.CacheControl = "no-cache";

    try
    {
        await foreach (var token in chat.StreamAsync(request, context.RequestAborted))
        {
            var frame = $"data: {JsonSerializer.Serialize(token)}\n\n";
            await context.Response.WriteAsync(frame, context.RequestAborted);
            await context.Response.Body.FlushAsync(context.RequestAborted);
        }

        await context.Response.WriteAsync("event: done\ndata: null\n\n", context.RequestAborted);
        await context.Response.Body.FlushAsync(context.RequestAborted);
    }
    catch (ClientResultException ex) when (ex.Status is 400 or 401 or 429)
    {
        if (!context.Response.HasStarted)
        {
            context.Response.StatusCode = ex.Status;
        }

        var message = ex.Status switch
        {
            401 => "Azure OpenAI authentication failed.",
            429 => "Azure OpenAI rate limit reached.",
            _ => "Azure OpenAI rejected the request."
        };
        await context.Response.WriteAsync(
            $"event: error\ndata: {JsonSerializer.Serialize(message)}\n\n",
            context.RequestAborted);
        await context.Response.Body.FlushAsync(context.RequestAborted);
    }
    catch (OperationCanceledException) when (context.RequestAborted.IsCancellationRequested)
    {
        // The client disconnected.
    }
});

app.Run();

The non-streaming endpoint returns one JSON response. The JSON streaming endpoint serializes the async sequence as an array. The POST SSE endpoint sends each text fragment as a JSON string. That escapes line breaks and backslashes inside the data field. After the first frame, the response status is committed, so an upstream failure can be reported as an SSE error event.

Step 8 — Handle Content Filter Responses

Azure OpenAI may reject a filtered prompt with an HTTP 400 error. Add the following middleware after the app is built and before the endpoints. Streaming can also signal filtering through the finish reason. See the content filter guide for the difference.

app.Use(async (context, next) =>
{
    try
    {
        await next();
    }
    catch (ClientResultException ex) when (
        ex.Status == 400 && !context.Response.HasStarted &&
        ex.Message.Contains("content_filter", StringComparison.OrdinalIgnoreCase))
    {
        context.Response.StatusCode = 400;
        await context.Response.WriteAsJsonAsync(new
        {
            error = "Content filter triggered",
            detail = "The request or response was flagged by Azure content safety."
        });
    }
});

Check the fix for 429 rate-limit errors and fix for 401 unauthorized errors if you run into those issues during development.

Step 9 — Test with curl

Start the application:

dotnet run --no-launch-profile -- --urls http://localhost:5000

Non-streaming request:

curl -X POST http://localhost:5000/api/chat \
  -H "Content-Type: application/json" \
  -d '{"message": "Explain dependency injection in three sentences."}'

You receive a single JSON payload with the full response, conversation ID, and token counts.

Streaming with SSE:

curl -X POST http://localhost:5000/api/chat/sse \
  -H "Content-Type: application/json" \
  -d '{"message": "What is async/await in C#?"}' \
  --no-buffer

Text deltas appear incrementally as JSON strings in data: lines. The --no-buffer flag ensures curl writes output as it arrives.

Multi-turn conversation:

# First message -- capture the conversationId
curl -X POST http://localhost:5000/api/chat \
  -H "Content-Type: application/json" \
  -d '{"message": "What is LINQ?"}'

# Follow-up using the returned conversationId
curl -X POST http://localhost:5000/api/chat \
  -H "Content-Type: application/json" \
  -d '{"message": "Show me an example.", "conversationId": "<id-from-above>"}'

The assistant remembers the first message and builds on it. This works because the conversation store accumulates the full message history and sends it with each request.

Step 10 — Consume SSE from a Browser

An HTTP chunk can end halfway through an event or a Unicode character. This example decodes the text as a stream and keeps each incomplete event until its blank-line delimiter arrives. Add an element with id=“output” and run the script from the same origin as the API.

async function streamChat(message) {
    const response = await fetch('/api/chat/sse', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ message })
    });

    if (!response.ok || !response.body) {
        throw new Error('Chat request failed (' + response.status + ')');
    }

    const output = document.getElementById('output');
    const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
    let pending = '';

    try {
        while (true) {
            const { done, value } = await reader.read();
            if (done) throw new Error('Chat ended before the completion event.');
            pending += value;

            let boundary;
            while ((boundary = pending.indexOf('\n\n')) !== -1) {
                const frame = pending.slice(0, boundary);
                pending = pending.slice(boundary + 2);
                const lines = frame.split('\n');
                if (lines.includes('event: done')) return;
                const data = lines.find(line => line.startsWith('data: '));
                if (!data) continue;

                const text = JSON.parse(data.slice(6));
                if (lines.includes('event: error')) throw new Error(text);
                output.textContent += text;
            }
        }
    } finally {
        await reader.cancel().catch(() => {});
    }
}

This reader matches the server above, which emits LF delimiters and one JSON string per text event. Use an SSE client library when consuming an API that emits other SSE formats. The native EventSource API opens GET requests, so this POST endpoint uses fetch.

Complete Project Structure

StreamingChatApi/
  Program.cs
  appsettings.json
  Models/
    AzureOpenAISettings.cs
    ChatRequest.cs
    ChatResponse.cs
  Services/
    ChatService.cs
    ConversationStore.cs

Assemble Program.cs from the registration, middleware and endpoint blocks in that order. Configure your endpoint and deployment, then supply your key through user secrets. The .NET build and a local HTTP check with scripted events were verified. A live model call requires your own Azure resource.

What You Learned

This workshop covered the full path from an empty directory to a local streaming chat API. You configured AzureOpenAIClient as a singleton with automatic retry. You built three endpoint patterns — synchronous JSON, IAsyncEnumerable streaming, and SSE — each suited to different client types. You handled 429, 401, and content filter errors at both the endpoint and middleware levels. Finally, you implemented conversation history management for multi-turn interactions.

The Azure OpenAI SDK on NuGet and the Azure OpenAI documentation are the authoritative references for everything shown here. The Azure.AI.OpenAI v2 release overview provides the historical context for the first GA v2 release.

For deeper prompt engineering techniques to improve response quality, continue with the Prompt Engineering Fundamentals in C# guide.

To understand how token consumption affects the cost and context limits of your streaming API, read Token Counting and Context Management in C# for Azure OpenAI.

If you want to add a real-time streaming chat UI without building a separate frontend, the Build a Streaming AI Chatbot with Blazor and Semantic Kernel workshop shows how to integrate this streaming API pattern directly into a Blazor Server component using SignalR and InvokeAsync(StateHasChanged).

For Semantic Kernel-specific streaming patterns, see Semantic Kernel Streaming in C#.

AI-Friendly Summary

Summary

Build a .NET 10 Minimal API with Azure OpenAI, in-memory conversation history, and three response formats. The browser example reads a POST SSE response with fetch and buffers partial frames so network chunk boundaries cannot split or discard text.

Key Takeaways

  • Register AzureOpenAIClient as a singleton with retry policy for resilient Azure OpenAI calls
  • Use CompleteChatStreamingAsync and IAsyncEnumerable to stream tokens to API consumers
  • Use fetch for the POST SSE endpoint and buffer incomplete event frames
  • Handle 429 rate-limit, 401 auth, and content-filter errors gracefully in middleware
  • Manage conversation history per session to maintain multi-turn context

Implementation Checklist

  • Scaffold .NET 10 Web API project and install Azure.AI.OpenAI 2.x
  • Register AzureOpenAIClient singleton with retry options in DI
  • Implement non-streaming /api/chat endpoint
  • Implement streaming /api/chat/stream endpoint with IAsyncEnumerable
  • Implement SSE /api/chat/sse endpoint for browser clients
  • Add conversation history model and per-session management
  • Add error handling for 429, 401, and content filter responses
  • Test all endpoints with curl

Frequently Asked Questions

Does Azure OpenAI support streaming in .NET?

Yes. CompleteChatStreamingAsync yields StreamingChatCompletionUpdate objects. Forward nonempty text fragments as they arrive. The time to the first fragment depends on the deployment, prompt and network.

How do I handle rate limiting with Azure OpenAI?

Register your AzureOpenAIClient with a retry pipeline. The SDK's AzureOpenAIClientOptions accepts a RetryPolicy that automatically retries on 429 Too Many Requests responses with exponential back-off. For additional control, read the Retry-After header and queue requests accordingly.

What is the difference between streaming and non-streaming chat completion?

A non-streaming request returns one complete response. A streaming request lets the UI display partial text before generation finishes.

How do I send streaming responses to a browser?

Send JSON-encoded text deltas as SSE data events and flush after each frame. Because this example sends a POST body, read it with fetch. Buffer partial events until the blank-line delimiter arrives.

You Might Also Enjoy

#Azure OpenAI #Chat Completion #Streaming #ASP.NET Core #.NET AI

Was this article useful?

Feedback is anonymous and helps us improve content quality.