Integrating ChatGPT in ASP.NET Core

With the rise of AI, integrating natural language processing tools like ChatGPT into web applications is becoming increasingly common. This post walks through how to integrate ChatGPT (using OpenAI’s API) into an ASP.NET Core application.

Integrating OpenAI ChatGPT in ASP.NET Core

Getting Started

Artificial Intelligence (AI) is no longer a futuristic concept; it's a reality transforming how we build and interact with web applications. One of the most revolutionary tools in this space is OpenAI ChatGPT, an AI language model developed by OpenAI that enables natural, human-like conversations. Integrating ChatGPT into your ASP.NET Core application can significantly enhance user interaction, support automation, and streamline user experience across multiple domains such as from customer support to personal assistants and educational tools.

ChatGPT can be integrated into your ASP.NET Core application to create intelligent, conversational experiences such as chatbots, AI assistants, or smart content generators. Whether you're building a chatbot, a smart assistant, or a tool that leverages language understanding, this guide will give you a strong foundation to start using OpenAI in your .NET projects.

What is ChatGPT?

ChatGPT (OpenAI) is a chatbot interface built on top of OpenAI's GPT (Generative Pre-trained Transformer) models. It can:
  • Answer questions
  • Help with writing and editing
  • Solve problems (math, coding, logic)
  • Hold natural conversations
  • Translate and summarize text
  • Generate creative content (stories, poetry, etc.)

Step-by-Step Integration

Prerequisites

Create a New ASP.NET Core Project
  1. Open Visual Studio
  2. Click Create a new project
  3. Select ASP.NET Core Web API
  4. Click Next
  5. Name your project (e.g., ChatGPTIntegration)
  6. Choose .NET 6 or later (recommend .NET 8 if available)
  7. Click Create

This creates a minimal API setup with default WeatherForecast controller. You can remove it if not needed.

Install Required NuGet Package

Install the HttpClientFactory and System.Text.Json if they're not already available. You can also use Newtonsoft.Json if preferred, but ASP.NET Core now supports System.Text.Json out-of-the-box.

Visit my previous post "Installing NuGet Packages: A Beginner's Guide" and "Working with HttpClient in ASP.NET Core" if you want to know how to install NuGet Packages and know more about HttpClientFactory

Create a Service to Call OpenAI API

Create a class OpenAIService.cs in the Services folder with this below code:

using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
public class OpenAIService
{
  private readonly HttpClient _httpClient;
  private readonly string _apiKey;
  public OpenAIService(HttpClient httpClient, IConfiguration config)
  {
    _httpClient = httpClient;
    _apiKey = config["OpenAI:ApiKey"];
  }
  public async Task<string> GetChatResponseAsync(string prompt)
  {
    var requestBody = new
    {
      model = "gpt-3.5-turbo",
      messages = new[]
      {
      new { role = "user", content = prompt }
    }
    };
    var requestJson = new StringContent(
    JsonSerializer.Serialize(requestBody),
    Encoding.UTF8,
    "application/json"
    );
    var request = new HttpRequestMessage(HttpMethod.Post, "https://api.openai.com/v1/chat/completions");
    request.Headers.Add("Authorization", $"Bearer {_apiKey}");
    request.Content = requestJson;
    var response = await _httpClient.SendAsync(request);
    response.EnsureSuccessStatusCode();
    var responseString = await response.Content.ReadAsStringAsync();
    using var doc = JsonDocument.Parse(responseString);
    var content = doc.RootElement
    .GetProperty("choices")[0]
    .GetProperty("message")
    .GetProperty("content")
    .GetString();
    return content?.Trim() ?? string.Empty;
  }
}

Register the Service in Program.cs
Add the following to your Program.cs file:
builder.Services.AddHttpClient<OpenAIService>();
builder.Services.AddScoped<OpenAIService>();

Also add your API key to appsettings.json:
"OpenAI": {
  "ApiKey": "your-openai-api-key"
}

Create an API Endpoint for Chat
Create a new controller ChatController.cs:
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
[ApiController]
[Route("api/[controller]")]
public class ChatController : ControllerBase
{
  private readonly OpenAIService _openAIService;
  public ChatController(OpenAIService openAIService)
  {
    _openAIService = openAIService;
  }
  [HttpPost]
  public async Task<IActionResult> Chat([FromBody] ChatRequest request)
  {
    if (string.IsNullOrWhiteSpace(request.Message))
    return BadRequest("Message is required.");
    var response = await _openAIService.GetChatResponseAsync(request.Message);
    return Ok(new { response });
  }
}
public class ChatRequest
{
public string Message { get; set; }
}

Test the API
You can now test your ChatGPT API using tools like:
  • Postman
  • Swagger UI (enabled by default in ASP.NET Core)
  • Frontend apps like React or Angular

Request Example:
POST /api/chat
Content-Type: application/json
{
  "message": "What is the capital of France?"
}

Response Example:
{
  "response": "The capital of France is Paris."
}

Summary

Integrating OpenAI ChatGPT into your ASP.NET Core application is a powerful way to bring intelligent conversation capabilities to your platform. Whether you're building a chatbot, support assistant, or educational tool, leveraging OpenAI’s models can significantly improve interactivity and engagement.

Thanks

Kailash Chandra Behera

I am an IT professional with over 13 years of experience in the full software development life cycle for Windows, services, and web-based applications using Microsoft .NET technologies.

Previous Post Next Post

نموذج الاتصال