AI-Driven Chatbot in .NET: Build One in Under an Hour

In this hands-on guide, we’ll show you how to build a fully functional AI-powered chatbot using .NET and OpenAI’s GPT models. Whether you’re a beginner exploring AI for the first time or an experienced developer looking to integrate chatbots into enterprise solutions, this article has you covered.
You’ll learn how to:
- Set up a .NET 8 Web API project
- Integrate OpenAI’s GPT model to process user messages
- Maintain conversation history using in-memory sessions
- Secure your chatbot API using custom middleware
- Deploy your solution locally, via Docker, or to Azure
This tutorial provides step-by-step instructions, complete code samples, and practical explanations to help you build an AI chatbot in under an hour.
By the end, you’ll have a chatbot ready for real-world use cases like customer support, product assistance, and lead qualification.
Table of Contents
- Part 1: Getting Started (Beginner)
- Part 2: Intermediate – Add Chat Memory & Context
- Part 3: Advanced – Secure and Deploy
- Real-World Use Cases
- Summary
Part 1: Getting Started (Beginner)
Step 1: Create a New ASP.NET Core Web API Project
dotnet new webapi -n AiChatbotDemo
cd AiChatbotDemo
If you’re passionate about .NET and love diving into development tips and insights, check out our latest articles at WireFuture’s .NET blog.
This command scaffolds a new Web API project named AiChatbotDemo
.
Step 2: Install Required NuGet Packages
dotnet add package Microsoft.Extensions.Http
dotnet add package OpenAI
These packages enable HTTP calls and access to OpenAI’s GPT API.
Step 3: Create the Model
Define models for user requests and AI responses.
public class ChatRequest
{
public string Message { get; set; }
public List<string> History { get; set; } = new();
}
public class ChatResponse
{
public string Reply { get; set; }
}
This model keeps track of the user’s message and chat history.
Step 4: Add OpenAI Service
This service interacts with OpenAI’s API.
public class OpenAiService
{
private readonly HttpClient _httpClient;
private readonly string _apiKey = "YOUR_OPENAI_API_KEY";
public OpenAiService(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<string> GetResponseAsync(List<string> history, string userMessage)
{
var prompt = string.Join("\n", history) + $"\nUser: {userMessage}\nAI:";
var requestBody = new
{
model = "gpt-3.5-turbo",
messages = new[]
{
new { role = "user", content = prompt }
}
};
var request = new HttpRequestMessage(HttpMethod.Post, "https://api.openai.com/v1/chat/completions")
{
Content = new StringContent(JsonConvert.SerializeObject(requestBody), Encoding.UTF8, "application/json")
};
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _apiKey);
var response = await _httpClient.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();
dynamic result = JsonConvert.DeserializeObject(content);
return result.choices[0].message.content;
}
}
Step 5: Register Services in Program.cs
Register the OpenAiService
for dependency injection.
builder.Services.AddHttpClient<OpenAiService>();
builder.Services.AddSingleton<OpenAiService>();
Step 6: Create the Controller
The controller handles incoming messages and returns AI replies.
[ApiController]
[Route("api/[controller]")]
public class ChatController : ControllerBase
{
private readonly OpenAiService _openAiService;
public ChatController(OpenAiService openAiService)
{
_openAiService = openAiService;
}
[HttpPost]
public async Task<IActionResult> Post([FromBody] ChatRequest request)
{
var reply = await _openAiService.GetResponseAsync(request.History, request.Message);
return Ok(new ChatResponse { Reply = reply });
}
}
Part 2: Intermediate – Add Chat Memory & Context
Add memory to your chatbot using in-memory storage per session.
🚀 Supercharge Your Business with AI Chatbots! 🤖💬
💡 Built on ASP.NET for performance. Trained with AI for intelligence.At WireFuture, we specialize in:
✅ Custom Chatbot Development
✅ Scalable ASP.NET Web Solutions
✅ GPT Integration for Smart Conversations
✅ Secure API & Real-Time Deployment🧠 From customer support to lead generation — automate smarter, not harder.
📈 Let’s build your AI-driven future!📩 Start your chatbot journey today:
🌐 wirefuture.com
📞 +91-9925192180
Create a Memory Store
public class MemoryStore
{
private readonly Dictionary<string, List<string>> _sessions = new();
public List<string> GetHistory(string sessionId)
{
if (!_sessions.ContainsKey(sessionId))
_sessions[sessionId] = new List<string>();
return _sessions[sessionId];
}
public void AddToHistory(string sessionId, string entry)
{
var history = GetHistory(sessionId);
history.Add(entry);
}
}
Update the Controller to Use Memory
[ApiController]
[Route("api/[controller]")]
public class ChatController : ControllerBase
{
private readonly OpenAiService _openAiService;
private readonly MemoryStore _memoryStore;
public ChatController(OpenAiService openAiService, MemoryStore memoryStore)
{
_openAiService = openAiService;
_memoryStore = memoryStore;
}
[HttpPost("{sessionId}")]
public async Task<IActionResult> Post(string sessionId, [FromBody] ChatRequest request)
{
var history = _memoryStore.GetHistory(sessionId);
history.Add($"User: {request.Message}");
var reply = await _openAiService.GetResponseAsync(history, request.Message);
history.Add($"AI: {reply}");
return Ok(new ChatResponse { Reply = reply });
}
}
Also register MemoryStore
in Program.cs
:
builder.Services.AddSingleton<MemoryStore>();
Part 3: Advanced – Secure and Deploy
1. API Key Middleware
Protect your API with a simple key check.
public class ApiKeyMiddleware
{
private readonly RequestDelegate _next;
private const string API_KEY = "your_secure_key_here";
public ApiKeyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
if (!context.Request.Headers.TryGetValue("X-Api-Key", out var extractedApiKey) || extractedApiKey != API_KEY)
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Unauthorized");
return;
}
await _next(context);
}
}
Register it in Program.cs
:
app.UseMiddleware<ApiKeyMiddleware>();
2. Hosting & Deployment Options
- Local:
dotnet run
- Docker: Use
Dockerfile
with port binding - Azure: Use Visual Studio publish or CI/CD with GitHub Actions
Real-World Use Cases
AI chatbots built with .NET are perfect for:
- Customer Support: Respond to FAQs and troubleshoot issues
- Lead Qualification: Collect information before routing to sales
- Internal Tools: Help employees query documentation or HR policies
- eCommerce: Recommend products, check order status, and more
Summary
In this comprehensive tutorial, you learned how to:
- Set up an AI chatbot using .NET and OpenAI
- Handle chat memory and context per session
- Protect your API with custom authentication
- Deploy your chatbot via multiple channels
This is just the beginning. You can now:
- Plug in database or Redis for long-term memory
- Integrate voice/text-to-speech for voice bots
- Use custom prompts and personas for branding
If you want help building or scaling your AI chatbot solution, feel free to reach out.
Step into the future with WireFuture at your side. Our developers harness the latest technologies to deliver solutions that are agile, robust, and ready to make an impact in the digital world.
No commitment required. Whether you’re a charity, business, start-up or you just have an idea – we’re happy to talk through your project.
Embrace a worry-free experience as we proactively update, secure, and optimize your software, enabling you to focus on what matters most – driving innovation and achieving your business goals.