Call an OpenAI model from a .NET API through Microsoft Foundry
Connect to a Foundry project without a key, send a request to a model deployment, and handle the answer and the guardrail results in ASP.NET Core.
Microsoft Foundry (formerly Azure AI Foundry) hosts OpenAI models inside your own Azure subscription. Your API calls a deployment of a model in a Foundry project, and it can sign in without an API key.
What you need
- A Foundry project with a model deployed. Your code asks for the deployment name, for example
summarizer. It doesn't have to match the model name. - The project endpoint. It looks like
https://<resource>.services.ai.azure.com/api/projects/<project>. - The Foundry User role (formerly Azure AI User) on the Foundry resource, for whoever calls it: your own account locally, and the app's managed identity in Azure.
- Packages:
Azure.AI.ProjectsandAzure.Identity. This note usesAzure.AI.Projects3.0.0, which brings inAzure.AI.Extensions.OpenAIandOpenAI.
1. Create one client for the app
The client is thread-safe, so register it once as a singleton.
using Azure.AI.Extensions.OpenAI;
using Azure.AI.Projects;
using Azure.Identity;
// The Responses types are still marked experimental in these packages.
#pragma warning disable OPENAI001, AAIP001, AAIP002
var project = new AIProjectClient(
new Uri(builder.Configuration["Foundry:ProjectEndpoint"]!),
new DefaultAzureCredential());
ProjectResponsesClient responses = project.ProjectOpenAIClient
.GetProjectResponsesClientForModel(builder.Configuration["Foundry:Deployment"]!);
builder.Services.AddSingleton(responses);There is no API key anywhere. DefaultAzureCredential uses your az login locally and the managed identity in Azure. It tries a chain of credentials, so in production you can swap in ManagedIdentityCredential to make the choice fixed.
2. Send a request
This uses the Responses API. The instructions set the model's job; the input is the user's text.
using System.ClientModel;
using OpenAI.Responses;
app.MapPost("/summarize", async (SummarizeRequest body, ProjectResponsesClient responses, CancellationToken ct) =>
{
var options = new CreateResponseOptions
{
Instructions = "Summarize the text in three short bullet points.",
StoredOutputEnabled = false, // don't keep this request on the service
MaxOutputTokenCount = 400,
};
options.InputItems.Add(ResponseItem.CreateUserMessageItem(body.Text));
ClientResult<ResponseResult> result = await responses.CreateResponseAsync(options, ct);
if (OutputBlocked(result))
return Results.UnprocessableEntity(new { error = "That text can't be processed." });
return Results.Ok(new { summary = result.Value.GetOutputText() });
});
record SummarizeRequest(string Text);StoredOutputEnabled = false sends store=false. By default a response is kept on the service for 30 days, so you can continue it with previous_response_id. If you send the whole conversation each time, you don't need that, and I'd rather not leave user data there. Microsoft notes that store=false isn't a guarantee of zero retention everywhere in the service, so read the data privacy page too.
3. Handle what the guardrails do
Guardrails (content filters) are set on the deployment and check both your input and the model's output. The two show up in different places.
- Your app sends the instructions and the user text
- Guardrail checks the inputInput blocked
HTTP 400error.code is content_filter, and the SDK throws ClientResultException. - Model writes the answer, guardrail checks the outputOutput blocked
content_filtersThe response comes back, and its entry for the output has blocked set to true. - Nothing blocked
HTTP 200Read the answer with GetOutputText().
A blocked input is an error. Catch it around the call:
using System.Text.Json;
try
{
// the call above
}
catch (ClientResultException e) when (e.Status == 400 && ErrorCode(e) == "content_filter")
{
// Retrying the same text won't help.
return Results.UnprocessableEntity(new { error = "That text can't be processed." });
}
catch (ClientResultException e)
{
logger.LogWarning("Model call failed with HTTP {Status}", e.Status); // status only
return Results.Problem("The model is unavailable right now.", statusCode: 503);
}
// Reads "error.code" from the error body without logging the body itself.
static string? ErrorCode(ClientResultException e)
{
var body = e.GetRawResponse()?.Content;
if (body is null) return null;
try
{
using var doc = JsonDocument.Parse(body);
return doc.RootElement.TryGetProperty("error", out var error)
&& error.ValueKind == JsonValueKind.Object
&& error.TryGetProperty("code", out var code)
? code.GetString()
: null;
}
catch (JsonException) { return null; }
}The output check is in the response itself. content_filters is a Foundry addition to the response, so the SDK has no property for it and you read it from the raw JSON:
// True when a guardrail blocked the model's output.
static bool OutputBlocked(ClientResult<ResponseResult> result)
{
using var doc = JsonDocument.Parse(result.GetRawResponse().Content);
if (!doc.RootElement.TryGetProperty("content_filters", out var filters)) return false;
return filters.EnumerateArray().Any(f =>
f.GetProperty("source_type").GetString() != "prompt" && f.GetProperty("blocked").GetBoolean());
}Log the status code, never the request or response body. Prompts can contain personal data.
4. Ask for JSON when code reads the answer
If your code parses the answer, ask for strict JSON that matches a schema instead of cleaning up free text.
options.TextOptions = new ResponseTextOptions
{
TextFormat = ResponseTextFormat.CreateJsonSchemaFormat(
"summary", BinaryData.FromString(schemaJson), jsonSchemaIsStrict: true),
};Check that it works
- A 401 or 403 usually means the identity that calls it doesn't have the Foundry User role on the Foundry resource.
- A 404 usually means the deployment name is wrong.
- Reasoning models don't take every setting. Most of them don't support
temperature, for example.
Sources
- Use the Azure OpenAI Responses API (Microsoft Learn)
- Azure.AI.Extensions.OpenAI for .NET (Microsoft Learn)
- Role-based access control for Foundry (Microsoft Learn)
- Credential chains in Azure Identity for .NET (Microsoft Learn)
- Data, privacy, and security for Foundry Models (Microsoft Learn)
- Structured outputs (Microsoft Learn)
- Azure OpenAI reasoning models (Microsoft Learn)
- OpenAI .NET library (GitHub)