π€ Integrating OpenAI with ASP.NET Core: Step-by-Step Guide
AI is no longer just hype—it's here, and it’s
practical. With OpenAI's API, you can bring intelligent features like chatbots,
content summarization, sentiment analysis, and code generation directly into
your .NET applications.
In this post, we'll walk through how to integrate
OpenAI into an ASP.NET Core MVC or Web API project, including
authentication, request/response handling, and best practices.
π¦ What You’ll Need
- .NET 6 or later
- OpenAI API Key (get it at platform.openai.com)
- HttpClient
- Optional: Newtonsoft.Json or
System.Text.Json for parsing
π Step-by-Step Integration
✅
Step 1: Create a New ASP.NET Core Project
bash
CopyEdit
dotnet new webapi -n OpenAIIntegrationDemo
cd OpenAIIntegrationDemo
✅
Step 2: Store Your OpenAI API Key Safely
In appsettings.json:
json
CopyEdit
"OpenAI": {
"ApiKey":
"your-api-key-here"
}
In Program.cs, register configuration:
csharp
CopyEdit
builder.Services.Configure<OpenAIOptions>(
builder.Configuration.GetSection("OpenAI"));
builder.Services.AddHttpClient();
Create a POCO class for options:
csharp
CopyEdit
public class OpenAIOptions
{
public
string ApiKey { get; set; }
}
✅
Step 3: Create a Service to Call OpenAI API
csharp
CopyEdit
public class OpenAIService
{
private
readonly IHttpClientFactory _httpClientFactory;
private
readonly OpenAIOptions _options;
public
OpenAIService(IHttpClientFactory httpClientFactory,
IOptions<OpenAIOptions> options)
{
_httpClientFactory = httpClientFactory;
_options = options.Value;
}
public
async Task<string> AskGPTAsync(string prompt)
{
var
client = _httpClientFactory.CreateClient();
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", _options.ApiKey);
var
request = new
{
model = "gpt-4",
messages = new[]
{
new { role = "user", content = prompt }
}
};
var
json = JsonConvert.SerializeObject(request);
var
response = await client.PostAsync(
"https://api.openai.com/v1/chat/completions",
new StringContent(json, Encoding.UTF8, "application/json"));
var
content = await response.Content.ReadAsStringAsync();
var
parsed = JObject.Parse(content);
return
parsed["choices"]?[0]?["message"]?["content"]?.ToString();
}
}
✅
Step 4: Register and Use the Service
In Program.cs:
csharp
CopyEdit
builder.Services.AddScoped<OpenAIService>();
In a controller:
csharp
CopyEdit
[ApiController]
[Route("api/[controller]")]
public class ChatController : ControllerBase
{
private
readonly OpenAIService _openAI;
public
ChatController(OpenAIService openAI)
{
_openAI = openAI;
}
[HttpPost("ask")]
public
async Task<IActionResult> Ask([FromBody] string prompt)
{
var response = await
_openAI.AskGPTAsync(prompt);
return
Ok(new { response });
}
}
π― Example Request
POST /api/chat/ask
Body:
json
CopyEdit
"What is Clean Architecture in simple
terms?"
Response:
json
CopyEdit
{
"response":
"Clean Architecture is a software design approach..."
}
π§ Use Cases
|
Use Case |
Example Feature |
|
Chatbot |
Live customer support assistant |
|
Summarization |
Summarize product reviews or emails |
|
Text generation |
Blog ideas, product descriptions, emails |
|
Code helper |
Generate code snippets or SQL queries |
|
Language translation |
Multi-lingual support |
π Best Practices
- Use rate-limiting to
avoid API quota issues
- Validate prompts to avoid
misuse or harmful inputs
- Consider streaming
responses for longer text (chat UX)
- Log errors and use retry
policies with Polly
π‘ Bonus: Streaming Support (Advanced)
For chat apps, you can enable streaming
responses from OpenAI’s API using HttpClient.SendAsync() and reading the
response stream. Let me know if you'd like a blog just for that!
π¦ Summary
Integrating OpenAI into your ASP.NET Core
project is straightforward, powerful, and opens the door to smart automation,
content creation, and natural language processing. With just a few lines of
code, your app can become smarter and more interactive.
Comments
Post a Comment