Introduction
Artificial Intelligence is becoming a core part of modern applications, from chatbots to content generation and smart automation. If you're a .NET developer, integrating OpenAI or Azure OpenAI into your C# .NET 9 application can unlock powerful AI capabilities such as text generation, summarization, and code assistance.
In this step-by-step guide, you will learn how to integrate OpenAI and Azure OpenAI APIs into a .NET 9 application in simple and practical terms. We will cover setup, configuration, coding, and best practices to ensure your integration is secure, scalable, and production-ready.
What You Need Before Starting
Before you begin, make sure you have the following:
.NET 9 SDK installed
A basic understanding of C# and Web APIs
An OpenAI API key OR Azure OpenAI resource
Visual Studio or VS Code
Step 1: Create a New .NET 9 Project
Start by creating a new console or Web API project.
dotnet new webapi -n OpenAIIntegrationDemo
cd OpenAIIntegrationDemo
This will create a clean Web API project where you can integrate AI services.
Step 2: Install Required NuGet Packages
Install the necessary packages to make HTTP calls and handle JSON.
dotnet add package Newtonsoft.Json
dotnet add package Microsoft.Extensions.Http
You can also use System.Text.Json if you prefer built-in JSON handling.
Step 3: Store API Keys Securely
Never hardcode your API keys. Use appsettings.json or environment variables.
Example:
{
"OpenAI": {
"ApiKey": "your-api-key"
}
}
For Azure OpenAI:
{
"AzureOpenAI": {
"Endpoint": "https://your-resource.openai.azure.com/",
"ApiKey": "your-api-key",
"DeploymentName": "your-deployment"
}
}
Step 4: Create a Service for OpenAI Integration
Create a service class to handle API calls.
public class OpenAIService
{
private readonly HttpClient _httpClient;
private readonly IConfiguration _config;
public OpenAIService(HttpClient httpClient, IConfiguration config)
{
_httpClient = httpClient;
_config = config;
}
public async Task<string> GetCompletionAsync(string prompt)
{
var apiKey = _config["OpenAI:ApiKey"];
_httpClient.DefaultRequestHeaders.Clear();
_httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
var requestBody = new
{
model = "gpt-4o-mini",
messages = new[]
{
new { role = "user", content = prompt }
}
};
var response = await _httpClient.PostAsJsonAsync("https://api.openai.com/v1/chat/completions", requestBody);
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadAsStringAsync();
return result;
}
}
Step 5: Register Service in Dependency Injection
Update Program.cs:
builder.Services.AddHttpClient<OpenAIService>();
Dependency Injection ensures your service is reusable and testable.
Step 6: Create an API Controller
Create a controller to expose your AI functionality.
[ApiController]
[Route("api/[controller]")]
public class AIController : ControllerBase
{
private readonly OpenAIService _service;
public AIController(OpenAIService service)
{
_service = service;
}
[HttpGet("ask")]
public async Task<IActionResult> Ask(string prompt)
{
var result = await _service.GetCompletionAsync(prompt);
return Ok(result);
}
}
Now you can call:
GET /api/ai/ask?prompt=Explain%20AI
Step 7: Azure OpenAI Integration (Alternative)
If you are using Azure OpenAI, the main difference is endpoint and headers.
Join the conversation! Your thoughts help the community grow.