📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Show me how you'd call Azure OpenAI from an ASP.NET Core API using Microsoft.Extensions.AI. How do you register IChatClient in DI, authenticate without keys, stream the reply to the browser, and handle timeouts and throttling?

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.

Junior Coding Intermediate ai aspnet-core azure-openai managed-identity microsoft-extensions-ai streaming

🎯 Key points

  • IChatClient is the provider-neutral abstraction in Microsoft.Extensions.AI (core packages GA since 2025; some provider adapters ship previews first, so pin versions); the OpenAI adapter exposes it via AsIChatClient()
  • AzureOpenAIClient with a token credential; the app's managed identity needs the Cognitive Services OpenAI User role; no API key in config
  • DefaultAzureCredential for local development; ManagedIdentityCredential (or DefaultAzureCredential restricted to it) in production to avoid the probing chain and picking up the wrong identity
  • builder.Services.AddChatClient(...) returns a ChatClientBuilder for middleware: UseLogging, UseOpenTelemetry, UseDistributedCache, UseFunctionInvocation
  • Register the client as a singleton; it is thread-safe and holds the HTTP pipeline
  • GetStreamingResponseAsync returns IAsyncEnumerable<ChatResponseUpdate>; return it from a minimal API or as server-sent events (TypedResults.ServerSentEvents in .NET 10); async all the way, never .Result
  • Pass HttpContext.RequestAborted so a closed browser tab stops generation and billing
  • Azure OpenAI throttles with 429 and retry-after; the Azure SDK retries with backoff, and you size TPM quota

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"I code against IChatClient from Microsoft.Extensions.AI rather than the raw OpenAI SDK, because it's the common abstraction across providers and it gives me a middleware pipeline. In Program.cs I create an AzureOpenAIClient with the endpoint from configuration and DefaultAzureCredential, get the chat client for my deployment name and call AsIChatClient(). I register that with AddChatClient, and chain UseOpenTelemetry() and UseLogging() so every call is traced with token counts. Locally DefaultAzureCredential picks up my az 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. GetStreamingResponseAsync gives me an IAsyncEnumerable<ChatResponseUpdate>; I project the text and return it, or in .NET 10 use TypedResults.ServerSentEvents so the browser can use EventSource. I pass HttpContext.RequestAborted all 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."


The pieces

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

Streaming options

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

Production example

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.

🔍 What the interviewer is checking

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

  • Uses IChatClient and AddChatClient with middleware
  • Keyless auth with managed identity and a named role
  • Streams and passes the request cancellation token
  • Mentions quotas, 429 and retries
  • Caps output tokens

Red flags

  • API key in configuration or source
  • New client per request or a static HttpClient hand-rolled call
  • No cancellation; blocking .Result calls
  • No idea what happens under load

📚 Learn in depth

1. Why an abstraction

Microsoft.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.

2. The middleware pipeline

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.

3. Keyless authentication

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.

4. How streaming works

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.

5. Throttling, timeouts and cancellation

  • Each deployment has a tokens-per-minute quota; bursts return 429 with retry-after. The Azure SDK pipeline retries with exponential backoff (configurable via AzureOpenAIClientOptions).
  • Set NetworkTimeout sensibly: long generations are legitimate, but a hung connection should not hold a request thread forever.
  • Cancellation flows from RequestAborted through GetStreamingResponseAsync to the HTTP call, stopping generation.

6. Data residency

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.

Try it yourself

  1. Build the endpoint below, call it with curl -N and watch tokens arrive.
  2. Close the request mid-stream and confirm in the logs that the call was cancelled.
  3. Add UseOpenTelemetry() and view the gen_ai spans and token attributes in the Aspire dashboard.
  4. Remove your Azure role assignment and observe the 401/403; restore it.
  5. Replace the real client with a fake IChatClient in a WebApplicationFactory test.

💻 Code

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>

⚠ Common mistakes

  • Mistake: Putting the API key in appsettings.json "for now". Why it is wrong: keys leak through git, logs and screenshots and are hard to rotate. Instead: a token credential with managed identity, and disable key auth on the resource.
  • Mistake: Using 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.
  • Mistake: Creating a new client per request. Why it is wrong: wasted handshakes and allocations; the client is thread-safe. Instead: register once as a singleton via AddChatClient.
  • Mistake: Calling 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.
  • Mistake: Not passing the request's cancellation token. Why it is wrong: generation continues and is billed after the user has left. Instead: flow RequestAborted (the endpoint's CancellationToken) into the call.
  • Mistake: Buffering the whole response before returning. Why it is wrong: users wait for the full generation. Instead: stream with GetStreamingResponseAsync and SSE or IAsyncEnumerable.
  • Mistake: Streaming output that must be validated (JSON, actions). Why it is wrong: the user sees or acts on unvalidated partial data. Instead: use a non-streaming call for structured output and validate it first.
  • Mistake: Coding directly against one vendor SDK everywhere. Why it is wrong: tests need the real service and switching models is painful. Instead: depend on IChatClient and fake it in tests.
  • Mistake: Ignoring 429s and quotas. Why it is wrong: peak traffic fails. Instead: size TPM quota, rely on SDK retries with backoff, and degrade gracefully.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions managed identity or configuration Why: Checks how they manage secrets and configuration beyond the AI client
    How to answer

    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.

  2. When: Candidate mentions UseOpenTelemetry Why: Checks whether they can trace and measure AI calls alongside the rest of the service
    How to answer

    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.

↩ Usually asked after

More in .NET and AI

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me