Calling Azure OpenAI from ASP.NET Core with Microsoft.Extensions.AI: AzureOpenAIClient with DefaultAzureCredential and managed identity, AddChatClient with the ChatClientBuilder pipeline, streaming with GetStreamingResponseAsync and IAsyncEnumerable or server-sent events, cancellation, and 429 handling.
Use Microsoft.Extensions.AI: build an AzureOpenAIClient with the endpoint and DefaultAzureCredential, take the chat client for your deployment and call AsIChatClient(). Register it once with builder.Services.AddChatClient(...), which returns a ChatClientBuilder so you can add logging, OpenTelemetry and caching as middleware. In Azure the app's managed identity gets the Cognitive Services OpenAI User role, so there is no key anywhere.
For streaming, call GetStreamingResponseAsync and return the IAsyncEnumerable (or server-sent events) so the first words reach the browser in under a second. Pass RequestAborted as the cancellation token. The trade-off: streaming improves perceived latency but you can't validate the whole answer before the user sees it.
"I code against
IChatClientfrom Microsoft.Extensions.AI rather than the raw OpenAI SDK, because it's the common abstraction across providers and it gives me a middleware pipeline. InProgram.csI create anAzureOpenAIClientwith the endpoint from configuration andDefaultAzureCredential, get the chat client for my deployment name and callAsIChatClient(). I register that withAddChatClient, and chainUseOpenTelemetry()andUseLogging()so every call is traced with token counts. LocallyDefaultAzureCredentialpicks up myaz login; in App Service or Container Apps it uses the managed identity, which I've granted the Cognitive Services OpenAI User role. No API key goes into appsettings or Key Vault at all.For the endpoint, a chat answer can take ten seconds to finish, so I stream.
GetStreamingResponseAsyncgives me anIAsyncEnumerable<ChatResponseUpdate>; I project the text and return it, or in .NET 10 useTypedResults.ServerSentEventsso the browser can useEventSource. I passHttpContext.RequestAbortedall the way down: if the user closes the tab, the HTTP call to Azure is cancelled and we stop paying for tokens nobody will read.The mistake I see is newing up a client per request, or putting the key in config 'just for now'. The client is thread-safe and should be a singleton, and keyless auth is no harder than a key. I also cap
MaxOutputTokens, set a sensible timeout, and let the Azure SDK's retry policy handle 429s, while making sure the deployment's tokens-per-minute quota fits our peak. Streaming makes it feel fast; quotas and cancellation keep it cheap."
| Piece | Package | Role |
|---|---|---|
IChatClient |
Microsoft.Extensions.AI.Abstractions | Provider-neutral chat API |
ChatClientBuilder middleware |
Microsoft.Extensions.AI | Logging, OpenTelemetry, caching, function invocation |
AsIChatClient() |
Microsoft.Extensions.AI.OpenAI | Adapts the OpenAI / Azure OpenAI client |
AzureOpenAIClient |
Azure.AI.OpenAI | Talks to your Azure OpenAI / Foundry resource |
DefaultAzureCredential |
Azure.Identity | Keyless auth: developer login locally, managed identity in Azure |
| Option | Client side | When |
|---|---|---|
Return IAsyncEnumerable<string> |
fetch and read the JSON array stream |
Simple, works with any HTTP client |
TypedResults.ServerSentEvents (.NET 10) |
EventSource or fetch reader |
Chat UIs; clear event framing |
| SignalR | SignalR client | Already using SignalR; bidirectional needs |
| No streaming | Normal JSON | Background jobs, structured output you must validate first |
Moving [an internal Q&A endpoint] from a blocking call to SSE streaming dropped time to first visible text from [about 7 s] to [about 600 ms] with the same total generation time. Wiring RequestAborted through cut wasted output tokens by [roughly 15%], because users often navigated away mid-answer.
Checks that the candidate can wire a real AI call into ASP.NET Core with current libraries, secure auth and good request hygiene.
Green flags
IChatClient and AddChatClient with middlewareRed flags
HttpClient hand-rolled call.Result callsMicrosoft.Extensions.AI (GA since 2025) defines IChatClient and IEmbeddingGenerator<TInput, TEmbedding>. Providers (Azure OpenAI, OpenAI, Ollama, Foundry Local and others) implement them, and higher-level frameworks such as the Microsoft Agent Framework build on them. Your code depends on the interface, so swapping a model or a provider, or faking it in tests, does not ripple through the app.
your code ─► UseLogging ─► UseOpenTelemetry ─► UseDistributedCache ─► UseFunctionInvocation ─► Azure OpenAI client ─► HTTPS
ChatClientBuilder wraps the inner client in DelegatingChatClient layers, exactly like HttpClient handlers or ASP.NET Core middleware. Order matters: caching outside function invocation caches the final answer; OpenTelemetry outermost records the whole call.
App Service / Container App ──(managed identity token from Entra ID)──► Azure OpenAI
role: Cognitive Services OpenAI User
DefaultAzureCredential tries environment credentials, workload identity, managed identity, then developer tools (Visual Studio, Azure CLI). In production, prefer ManagedIdentityCredential directly to avoid the probing chain and its start-up latency. Disabling local (key) auth on the resource enforces the policy.
The service sends server-sent events over one HTTP response, one chunk per few tokens. The SDK exposes them as IAsyncEnumerable<ChatResponseUpdate>. ASP.NET Core writes each item as it arrives when you return an IAsyncEnumerable and flushes the response. Proxies that buffer (some reverse proxies, response compression) can defeat streaming, so test through the real ingress.
retry-after. The Azure SDK pipeline retries with exponential backoff (configurable via AzureOpenAIClientOptions).NetworkTimeout sensibly: long generations are legitimate, but a hung connection should not hold a request thread forever.RequestAborted through GetStreamingResponseAsync to the HTTP call, stopping generation.For Australian personal information, pick a deployment type whose processing location you can defend: a Standard (regional) deployment in Australia East keeps processing in that region, while Global deployments may route anywhere. Note the choice in your privacy assessment.
curl -N and watch tokens arrive.UseOpenTelemetry() and view the gen_ai spans and token attributes in the Aspire dashboard.IChatClient in a WebApplicationFactory test.Registration and a streaming endpoint (.NET 10 minimal API). Packages: Microsoft.Extensions.AI, Microsoft.Extensions.AI.OpenAI, Azure.AI.OpenAI, Azure.Identity.
// Program.cs
using System.Runtime.CompilerServices;
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Extensions.AI;
var builder = WebApplication.CreateBuilder(args);
var endpoint = new Uri(builder.Configuration["AzureOpenAI:Endpoint"]
?? throw new InvalidOperationException("AzureOpenAI:Endpoint missing"));
var deployment = builder.Configuration["AzureOpenAI:ChatDeployment"] ?? "gpt-4.1-mini";
// One thread-safe client for the app. Keyless: managed identity in Azure, az login locally.
builder.Services
.AddChatClient(new AzureOpenAIClient(endpoint, new DefaultAzureCredential())
.GetChatClient(deployment)
.AsIChatClient())
.UseOpenTelemetry() // gen_ai spans with token usage
.UseLogging();
var app = builder.Build();
app.MapPost("/api/chat/stream", (AskRequest request, IChatClient chat, CancellationToken ct) =>
TypedResults.ServerSentEvents(StreamAnswer(chat, request.Question, ct), eventType: "token"));
app.Run();
static async IAsyncEnumerable<string> StreamAnswer(
IChatClient chat, string question, [EnumeratorCancellation] CancellationToken ct)
{
List<ChatMessage> messages =
[
new(ChatRole.System, "You answer questions about our public product documentation. Be brief."),
new(ChatRole.User, question)
];
var options = new ChatOptions { MaxOutputTokens = 500 };
// ct is RequestAborted: a closed tab cancels the upstream call and stops billing.
await foreach (var update in chat.GetStreamingResponseAsync(messages, options, ct))
{
if (!string.IsNullOrEmpty(update.Text))
yield return update.Text;
}
}
public sealed record AskRequest(string Question);
Configuration holds only non-secret values:
{
"AzureOpenAI": {
"Endpoint": "https://my-aoai-aue.openai.azure.com/",
"ChatDeployment": "gpt-4.1-mini"
}
}
Grant the app's managed identity access (once, in IaC or CLI):
az role assignment create \
--assignee <managed-identity-principal-id> \
--role "Cognitive Services OpenAI User" \
--scope <azure-openai-resource-id>
DefaultAzureCredential unchanged in production. Why it is wrong: it probes several credential sources, adding start-up latency, and can pick up an unexpected identity (for example environment variables left on a host). Instead: use ManagedIdentityCredential in production (or exclude the other sources) and keep DefaultAzureCredential for local development.AddChatClient.GetResponseAsync(...).Result or .Wait() in a controller. Why it is wrong: an LLM call can take seconds; blocking holds a thread-pool thread for the whole call and causes thread-pool starvation under load. Instead: async all the way, await every call and await foreach the stream.RequestAborted (the endpoint's CancellationToken) into the call.GetStreamingResponseAsync and SSE or IAsyncEnumerable.IChatClient and fake it in tests.The abstraction is the main win: IChatClient plus the builder pipeline gives you telemetry, caching, function calling and testability in one place, and the Agent Framework builds on the same interfaces. Keep provider specifics (endpoint, deployment, credential) in the composition root only.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
IChatClient via Microsoft.Extensions.AI |
Most app features | Thin layer | Need a provider-only feature not yet surfaced (use the raw client through GetService) |
| Raw Azure.AI.OpenAI SDK | Provider-specific APIs | Couples code to vendor | General app code |
| Agent Framework | Multi-step agents, tools, workflows | More concepts | A single prompt-and-answer call |
Measure time to first token and total duration separately; users judge the first, your bill tracks the second.
I'd inventory and classify every setting first: secrets, environment-specific values, shared values, and which must change live. Secrets go to Key Vault. Non-secret settings and feature flags go to Azure App Configuration with a label per environment, and secrets are referenced from there through Key Vault references. The app authenticates with its managed identity using least-privilege roles, and where possible secrets disappear entirely through passwordless Entra ID auth to SQL, Storage and Service Bus.
For refresh, use a sentinel key with a refresh interval and a secret refresh interval, and read live values through IOptionsMonitor. Rotation uses overlapping versions, so old and new both work during the window. Add start-up timeouts and replicas, and keep ValidateOnStart.
The trade-off: central, audited, rotatable configuration, in exchange for a network dependency at start-up that you must design for.
OpenTelemetry gives you three correlated signals: traces (a span per operation, linked by trace id), metrics (cheap aggregated counters and histograms) and logs (events that carry the TraceId and SpanId of the span they were written in).
In .NET the runtime already emits Activity and Meter data; you call AddOpenTelemetry() with WithTracing, WithMetrics and WithLogging, set a resource (service.name), and choose an exporter: UseOtlpExporter() for any OTLP back end or Collector (endpoint from OTEL_EXPORTER_OTLP_ENDPOINT or options), or the Azure Monitor distro (UseAzureMonitor()) for Application Insights.
For cost: metrics for rates and latency (never sampled), sampled traces (the distro now defaults to a rate-limited sampler of 5 traces per second, which adapts the kept percentage to load; you can change the rate or switch to a fixed SamplingRatio), level-filtered logs, and tail sampling in a Collector, configured with policies to keep errors and slow traces. The trade-off is completeness versus ingestion cost.
Last updated 23 Nov 2026.