When a .NET application uses an AI model, it is tempting to connect directly to the model provider. The application stores the endpoint and credentials, sends prompts, and processes the responses. This approach works well when there is only one application and one model. However, as an organization starts using multiple AI models across different applications, managing those connections becomes more complicated.
Each application may have its own API keys, model configuration, request limits, and logging implementation. Changing a model provider can require updates across several projects. It also becomes difficult for administrators to understand how much each application is using AI services.
Azure AI Gateway addresses this problem by providing a central entry point for AI model traffic. Instead of connecting directly to a model provider, a .NET application sends its requests to the gateway. The gateway authenticates the application, evaluates applicable policies, routes the request to the configured model, and returns the response.
This approach allows developers to integrate AI into their applications without managing every provider connection independently. It also gives platform teams a central place to control model access, credentials, usage, and monitoring.
In this article, we will connect a .NET application to Azure AI Gateway using C# and HttpClient. We will configure the gateway, send a chat completion request, handle the response, and look at how the same integration can be used in a larger application.
Understanding Azure AI Gateway
Azure AI Gateway provides a managed environment for publishing and governing access to AI models and Model Context Protocol (MCP) tools. It separates the application that makes an AI request from the service that actually executes the model.
For example, an organization might use Microsoft Foundry for one model and another provider for a different workload. Without a gateway, each application needs to know how to connect to its selected provider. The application also needs to manage the corresponding credentials and endpoint configuration.
With Azure AI Gateway, administrators register the model backends and expose them through gateway endpoints. Applications use the gateway connection details rather than connecting directly to each provider.
One important concept is the model alias. An alias gives an application a callable model name that is separate from the underlying deployment. If the platform team changes the backend deployment, the application can continue using the same alias, provided the new backend supports the same request contract.
The gateway also separates two authentication responsibilities:
The application authenticates to the gateway using a runtime API key or a supported Microsoft Entra ID identity.
The gateway authenticates to the backend model using its configured credentials, which can include a managed identity where supported.
This separation is valuable because the application does not need to store the backend provider's credentials.
It is worth distinguishing the dedicated Azure AI Gateway product from the AI gateway capabilities available in Azure API Management. Azure API Management provides AI-specific policies and gateway features within its existing API management service. The dedicated AI Gateway is a separate managed product with its own resource model and runtime endpoints. They are related, but they should not be treated as the same deployment experience.
Preparing Azure AI Gateway
Before writing the C# integration, configure the gateway and register a model that supports the API format your application intends to use.
You need an Azure subscription with the required permissions, a Microsoft Foundry account with a deployed chat model, and access to the AI Gateway management experience.
Create the gateway in the Azure portal or through the supported management tools. During configuration, review the networking settings carefully. The networking configuration selected during gateway creation can affect how the gateway reaches its backend services, and some settings are not editable after creation.
After the gateway is ready, add a model from Microsoft Foundry. Select the Foundry account containing your deployment and configure the gateway's backend authentication. For an Azure-hosted model, a system-assigned managed identity is a useful option when the required permissions and service support are available.
The gateway can then create aliases for the imported model deployments. These aliases are the names that applications use in their requests.
For example, an alias might look like this:
company-ai/gpt-chatThe actual alias depends on the model registration and gateway configuration. Always copy the callable name shown in the gateway rather than assuming that the backend deployment name and alias are identical.
Next, create a runtime API key under the gateway's access settings. This key allows an application to call the gateway. It is different from the credential the gateway uses to access the backend model.
Treat the runtime key as a sensitive credential. It grants access to the gateway's published resources according to its configured access model, so do not commit it to source control or place it directly in a desktop application's executable configuration.
Understanding the Gateway Endpoint
For OpenAI-compatible model APIs, Azure AI Gateway provides a common endpoint structure. A chat completion request uses the following pattern:
https://<gateway-host>/default/models/openai/v1/chat/completionsReplace the host with the endpoint displayed for your gateway. Do not construct the hostname from the gateway's display name because the actual endpoint may include region and service-specific identifiers.
The request uses a model alias in the model property. This is an important difference from a direct provider integration: the application identifies the published model through the gateway rather than configuring the underlying backend deployment itself.
A basic request body looks like this:
{
"model": "company-ai/gpt-chat",
"messages": [
{
"role": "user",
"content": "Explain dependency injection in C#."
}
]
}The gateway runtime API key can be sent through the Authorization header using the Bearer scheme. The exact authentication options depend on the gateway configuration, so use the authentication method supported by your environment.
Creating a .NET Application
Create a console application to test the connection before integrating it into an ASP.NET Core API, worker service, or desktop application.
dotnet new console -n AzureAIGatewayDemo
cd AzureAIGatewayDemoFor this example, use the built-in HttpClient API. Since the gateway exposes an OpenAI-compatible chat completions endpoint, the application can send a standard HTTP request without requiring a provider-specific SDK.
Store the gateway endpoint and runtime API key outside the source code. For local development, environment variables are a simple option.
For example, in PowerShell:
$env:AI_GATEWAY_URL = "https://your-gateway-host/default/models/openai/v1/chat/completions"
$env:AI_GATEWAY_API_KEY = "your-runtime-api-key"
$env:AI_GATEWAY_MODEL = "company-ai/gpt-chat"Use the actual endpoint and alias from your gateway configuration.
Environment variables help keep credentials out of the source code, but they are not a complete secrets-management solution for production. In an Azure-hosted application, consider an appropriate identity-based authentication approach or a secure secret store based on the gateway's supported authentication options.
Sending a Chat Completion Request From C#
The first implementation can use a small service that accepts a prompt and returns the model's response.
Create a class named AzureAIGatewayClient:
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
public sealed class AzureAIGatewayClient
{
private readonly HttpClient _httpClient;
private readonly string _model;
public AzureAIGatewayClient(
HttpClient httpClient,
string endpoint,
string apiKey,
string model)
{
_httpClient = httpClient;
_httpClient.BaseAddress = new Uri(endpoint);
_httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", apiKey);
_model = model;
}
public async Task<string> GetResponseAsync(
string prompt,
CancellationToken cancellationToken = default)
{
var request = new
{
model = _model,
messages = new[]
{
new
{
role = "user",
content = prompt
}
}
};
using var response = await _httpClient.PostAsJsonAsync(
"",
request,
cancellationToken);
response.EnsureSuccessStatusCode();
using var json = await JsonDocument.ParseAsync(
await response.Content.ReadAsStreamAsync(
cancellationToken),
cancellationToken: cancellationToken);
return json.RootElement
.GetProperty("choices")[0]
.GetProperty("message")
.GetProperty("content")
.GetString() ?? string.Empty;
}
}
Join the conversation! Your thoughts help the community grow.