AI Agents  

Building AI Chatbots in ASP.NET Core

Integrating OpenAI GPT with ASP.NET Core: Build Chatbots and Copilots

Artificial intelligence is transforming how we build applications. With OpenAI’s GPT models, developers can add natural language capabilities to their apps—from conversational chatbots to intelligent copilots that assist with tasks. ASP.NET Core provides the perfect foundation to integrate these models into scalable, production-ready solutions.

In this article, we’ll walk through the process of connecting GPT with ASP.NET Core using C#. You’ll learn how to configure the API, build a service layer, and expose endpoints that deliver AI responses.

Prerequisites

Before starting, make sure you have:

  • .NET 8 SDK

  • Visual Studio 2022 or VS Code

  • An OpenAI API key

  • Basic knowledge of ASP.NET Core Web API

  • NuGet Package Manager

Step 1: Create a New Project

Generate a Web API project:

dotnet new webapi -n GPTIntegrationDemo
cd GPTIntegrationDemo
dotnet run

Step 2: Install Dependencies

Add the required packages:

dotnet add package Microsoft.Extensions.Http
dotnet add package Newtonsoft.Json

Step 3: Configure OpenAI Settings

Add the configuration in appsettings.json:

{
  "OpenAI": {
    "ApiKey": "YOUR_API_KEY",
    "BaseUrl": "https://api.openai.com/v1/chat/completions",
    "Model": "gpt-4o-mini"
  }
}

Create a settings model:

public class OpenAISettings
{
    public string ApiKey { get; set; }
    public string BaseUrl { get; set; }
    public string Model { get; set; }
}

Step 4: Define Request and Response Models

GPTRequest.cs

public class GPTRequest
{
    public string Prompt { get; set; }
}

GPTResponse.cs

public class GPTResponse
{
    public string Content { get; set; }
}

Step 5: Build the GPT Service

Create Services/GPTService.cs:

using System.Text;
using Newtonsoft.Json;

public class GPTService
{
    private readonly HttpClient _httpClient;
    private readonly IConfiguration _configuration;

    public GPTService(HttpClient httpClient, IConfiguration configuration)
    {
        _httpClient = httpClient;
        _configuration = configuration;
    }

    public async Task<string> GetResponseAsync(string prompt)
    {
        var apiKey = _configuration["OpenAI:ApiKey"];
        var model = _configuration["OpenAI:Model"];
        var endpoint = _configuration["OpenAI:BaseUrl"];

        _httpClient.DefaultRequestHeaders.Clear();
        _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");

        var requestBody = new
        {
            model,
            messages = new[]
            {
                new { role = "user", content = prompt }
            }
        };

        var json = JsonConvert.SerializeObject(requestBody);
        var content = new StringContent(json, Encoding.UTF8, "application/json");

        var response = await _httpClient.PostAsync(endpoint, content);
        response.EnsureSuccessStatusCode();

        return await response.Content.ReadAsStringAsync();
    }
}

Step 6: Register Services

Update Program.cs:

builder.Services.AddHttpClient();
builder.Services.AddScoped<GPTService>();

Step 7: Create the API Controller

Create Controllers/GPTController.cs:

using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class GPTController : ControllerBase
{
    private readonly GPTService _gptService;

    public GPTController(GPTService gptService)
    {
        _gptService = gptService;
    }

    [HttpPost]
    public async Task<IActionResult> Ask(GPTRequest request)
    {
        var result = await _gptService.GetResponseAsync(request.Prompt);
        return Ok(result);
    }
}

Step 8: Test the Endpoint

Send a POST request.

Endpoint

/api/gpt

Request Body

{
  "prompt": "Explain dependency injection in .NET"
}

Response

{
  "content": "Dependency Injection is a design pattern..."
}

Step 9: Production Best Practices

To build a secure and scalable solution:

  • Secure API keys using environment variables or secret managers.

  • Rate limit requests to prevent misuse.

  • Log and monitor with Serilog or Application Insights.

  • Cache responses for repeated queries to save costs.

Real-World Use Cases

OpenAI GPT can power a wide range of applications:

  • Chatbots – customer support and virtual assistants

  • Copilots – developer helpers and productivity tools

  • Document intelligence – summarization and analysis

  • Knowledge base search – semantic search with vector databases

  • Content generation – technical documentation, reports, and blogs

Summary

OpenAI GPT can be integrated into ASP.NET Core applications through a simple service layer that uses HttpClient to communicate with the API. By configuring API settings, defining request and response models, registering services through dependency injection, and exposing REST endpoints, developers can quickly add conversational AI capabilities to their applications. With proper security, monitoring, caching, and rate limiting, this integration can support production-grade chatbots, copilots, document intelligence solutions, and enterprise AI assistants.