Sunday, September 14, 2025

Building a ChatGPT Chatbot in ASP.NET WebForms

 

Build a Simple ChatGPT WebForm App in ASP.NET (C#)

If you want to integrate ChatGPT into your ASP.NET WebForms project, here’s a step-by-step guide with complete code. We’ll create a small app where users can type prompts, send them to the OpenAI API, and display the assistant’s response — just like a mini chat interface.

Step 1: Define Models (Models.cs)

Create a folder named Models and add a file called MoModels.cs..Models.cs

.
This file defines the data structures for requests and responses.
using System;

namespace ChatGPT.Models
{
    public class ChatMessage
    {
        public string Role { get; set; } = string.Empty;
        public string Content { get; set; } = string.Empty;
    }

    public class Usage
    {
        public int? Prompt_Tokens { get; set; }
        public int? Completion_Tokens { get; set; }
        public int? Total_Tokens { get; set; }
    }

    public class Choice
    {
        public int Index { get; set; }
        public ChatMessage? Message { get; set; }
        public string? Finish_Reason { get; set; }
    }

    public class ChatResponse
    {
        public string? Id { get; set; }
        public string? Object { get; set; }
        public int Created { get; set; }
        public string? Model { get; set; }
        public Choice[]? Choices { get; set; }
        public Usage? Usage { get; set; }
    }

    public class ChatRequest
    {
        public string model { get; set; } = string.Empty;
        public ChatMessage[]? messages { get; set; }
        public int? max_tokens { get; set; }
    }
}

Step 2: Create OpenAI Client (OpenAiClient.cs)

Now, add a Controller folder and create OpenAiClient.cs.
This class handles communication with the OpenAI API.

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using ChatGPT.Models;

namespace ChatGPT.Controller
{
    public class OpenAiClient : IDisposable
    {
        private readonly HttpClient _httpClient;
        private readonly string _apiKey;
        private bool _disposed;

        public OpenAiClient(string apiKey)
        {
            _apiKey = apiKey ?? throw new ArgumentNullException(nameof(apiKey));
            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _apiKey);
        }

        public async Task<ChatMessage> GetChatCompletionAsync(List<ChatMessage> conversationHistory)
        {
            if (conversationHistory == null) throw new ArgumentNullException(nameof(conversationHistory));

            var requestData = new ChatRequest
            {
                model = "gpt-3.5-turbo",   // Change to your preferred model
                messages = conversationHistory.ToArray(),
                max_tokens = 150
            };

            var jsonPayload = JsonConvert.SerializeObject(requestData);
            var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
            var apiUrl = "https://api.openai.com/v1/chat/completions";

            try
            {
                HttpResponseMessage response = await _httpClient.PostAsync(apiUrl, content).ConfigureAwait(false);
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                var chatResponse = JsonConvert.DeserializeObject<ChatResponse>(responseBody);

                if (chatResponse?.Choices?.Length > 0)
                {
                    return chatResponse.Choices[0].Message ?? new ChatMessage { Role = "assistant", Content = string.Empty };
                }

                return new ChatMessage { Role = "assistant", Content = "No response received." };
            }
            catch (HttpRequestException ex)
            {
                return new ChatMessage { Role = "assistant", Content = $"Error calling OpenAI API: {ex.Message}" };
            }
        }

        public void Dispose()
        {
            if (!_disposed)
            {
                _httpClient?.Dispose();
                _disposed = true;
            }
        }
    }
}

Step 3: Build the Frontend (Home.aspx)

Create a new WebForm page named Home.aspx.
This will provide the UI for sending prompts and displaying responses.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Home.aspx.cs" Inherits="ChatGPT.Home" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>ChatGPT WebForm</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table width="99%">
                <tr>
                    <td>
                        <asp:TextBox ID="PromptTextBox" runat="server" 
                                     TextMode="MultiLine" Rows="5" Width="400" style="width:100%;"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Button ID="SendButton" runat="server" 
                                    Text="Get AI Response" OnClick="SendButton_Click" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <div id="chatWindow" runat="server" 
                             style="height: 400px; overflow-y: scroll; border: 1px solid #ccc; padding: 10px;">
                            <!-- Chat history will appear here -->
                        </div>
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>

Step 4: Handle Backend Logic (Home.aspx.cs)

Finally, implement the backend logic in Home.aspx.cs.

using System;
using System.Collections.Generic;
using System.Web.UI;
using ChatGPT.Models;
using ChatGPT.Controller;

namespace ChatGPT
{
    public partial class Home : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected async void SendButton_Click(object sender, EventArgs e)
        {
            string apiKey = "YOUR_API_KEY";   // Replace with your API key

            using (var openAiClient = new OpenAiClient(apiKey))
            {
                if (ViewState["ConversationHistory"] == null)
                {
                    ViewState["ConversationHistory"] = new List<ChatMessage>();
                }

                var conversationHistory = (List<ChatMessage>)ViewState["ConversationHistory"];
                string promptText = PromptTextBox.Text;

                if (!string.IsNullOrWhiteSpace(promptText))
                {
                    conversationHistory.Add(new ChatMessage { Role = "user", Content = promptText });
                    var aiResponse = await openAiClient.GetChatCompletionAsync(conversationHistory);
                    conversationHistory.Add(aiResponse);

                    // Save state
                    ViewState["ConversationHistory"] = conversationHistory;

                    // Clear textbox
                    PromptTextBox.Text = string.Empty;

                    // Render chat
                    RenderChatWindow(conversationHistory);
                }
            }
        }

        private void RenderChatWindow(List<ChatMessage> conversationHistory)
        {
            chatWindow.InnerHtml = string.Empty;

            foreach (var message in conversationHistory)
            {
                string cssClass = (message.Role == "user") ? "user-message" : "assistant-message";
                chatWindow.InnerHtml += $"<div class=\"{cssClass}\"><b>{message.Role}:</b><pre>{System.Web.HttpUtility.HtmlEncode(message.Content)}</pre></div>";
            }
        }
    }
}

If you are using.net framework < 4.6 then use below method to call api


public string GetChatCompletion(string promptText, string selectedModel)
{
    var requestData = new ChatRequest
    {
        model = selectedModel,
        messages = new ChatMessage[]
        {
            new ChatMessage { role = "user", content = promptText }
        }
    };

    var jsonPayload = JsonConvert.SerializeObject(requestData);
    var apiUrl = "https://api.openai.com/v1/chat/completions";

    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiUrl);
        request.Method = "POST";
        request.ContentType = "application/json";
        request.Headers["Authorization"] = "Bearer " + _apiKey;

        byte[] bytes = Encoding.UTF8.GetBytes(jsonPayload);

        using (Stream stream = request.GetRequestStream())
        {
            stream.Write(bytes, 0, bytes.Length);
            stream.Close();
        }

        WebResponse response = request.GetResponse();
        using (var reader = new StreamReader(response.GetResponseStream()))
        {
            var responseBody = reader.ReadToEnd();
            var chatResponse = JsonConvert.DeserializeObject<ChatResponse>(responseBody);

            if (chatResponse?.Choices?.Length > 0)
            {
                return pichatResponse.Choices[0].Message.Content.Trim();
            }
            return "No response received.";
        }
    }
    catch (HttpRequestException ex)
    {
        return $"Error calling OpenAI API: {ex.Message}";
    }
}






No comments:

Post a Comment