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:
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.
public async Task<string> GetAzureCompletionAsync(string prompt)
{
var endpoint = _config["AzureOpenAI:Endpoint"];
var apiKey = _config["AzureOpenAI:ApiKey"];
var deployment = _config["AzureOpenAI:DeploymentName"];
_httpClient.DefaultRequestHeaders.Clear();
_httpClient.DefaultRequestHeaders.Add("api-key", apiKey);
var url = $"{endpoint}openai/deployments/{deployment}/chat/completions?api-version=2024-02-15-preview";
var requestBody = new
{
messages = new[]
{
new { role = "user", content = prompt }
}
};
var response = await _httpClient.PostAsJsonAsync(url, requestBody);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
Step 8: Parse and Format Response
Instead of returning raw JSON, extract meaningful content.
var json = JObject.Parse(result);
var content = json["choices"][0]["message"]["content"].ToString();
Return only the AI-generated text for a cleaner API.
Step 9: Add Error Handling and Logging
Production apps must handle failures gracefully.
Example:
try
{
var result = await _service.GetCompletionAsync(prompt);
}
catch(Exception ex)
{
_logger.LogError(ex, "Error calling OpenAI API");
}
Step 10: Best Practices for Secure and Scalable Integration
Never expose API keys in frontend
Use Azure Key Vault or Secret Manager
Implement retry policies
Cache frequent responses
Limit token usage to control cost
Difference Between OpenAI and Azure OpenAI
| Feature | OpenAI API | Azure OpenAI |
|---|
| Hosting | OpenAI Cloud | Microsoft Azure |
| Authentication | Bearer Token | API Key Header |
| Endpoint | Fixed | Custom Endpoint |
| Enterprise Support | Limited | Strong Azure Integration |
| Compliance | Standard | Enterprise-grade compliance |
Real-World Use Cases
Here are some practical use cases you can build:
AI Chatbot for customer support
Content generator for blogs and SEO
Code assistant for developers
Email automation system
Document summarization tool
Conclusion
Integrating OpenAI or Azure OpenAI into a C# .NET 9 application is straightforward when broken down step by step. By using HttpClient, secure configuration, and proper architecture, you can build powerful AI-driven applications quickly.
Start small, experiment with prompts, and gradually enhance your application with advanced AI features like streaming responses, embeddings, and function calling. This integration can significantly improve user experience and automation capabilities in modern software systems.