Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Resources
    • Cheatsheets
    • Tech Comparisons
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# ASP.NET MVC ASP.NET Web Forms C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet General Web Development HTML, CSS HTML/CSS Java JavaScript JavaScript, HTML, CSS JavaScript, Node.js Node.js
      Python Python 3.11, Pandas, SQL Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. ASP.NET MVC
  4. Integrating ChatGPT API in ASP.NET

Integrating ChatGPT API in ASP.NET

Date- Aug 16,2024 Updated Feb 2026 6416 Free Download

Integrating ChatGPT API in ASP.NET MVC

In this tutorial, we'll explore how to integrate the ChatGPT API into an ASP.NET MVC application. The ChatGPT API, provided by OpenAI, allows developers to interact with the powerful language model for various applications like chatbots, content generation, and more.

Prerequisites

Before you begin, ensure you have:

  • An ASP.NET MVC project set up.
  • A valid API key from OpenAI for accessing the ChatGPT API.
  • The Newtonsoft.Json package installed for handling JSON serialization.

Step-by-Step Code Explanation

1. Setting Up the Controller

The first step is to create a controller named HomeController that will handle the API integration. Here's a breakdown of the key components:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

Imports: The necessary namespaces are imported, including Newtonsoft.Json for JSON serialization and System.Net.Http for making HTTP requests.

2. Defining the API URL

private static readonly string apiUrl = "https://api.openai.com/v1/chat/completions";

API URL: The API endpoint for sending requests to the ChatGPT API is defined as a static string.

3. Creating the Index Action

public ActionResult Index()
{
    return View();
}

Index Action: The Index action returns the default view for the HomeController. This view could contain a form where users can input their prompts.

4. Handling the POST Request

[HttpPost]
public async Task<ActionResult> GetChatGptResponse(string prompt)
{
    var response = await GetChatGPTResponseAsync(prompt);
    return Json(response);
}

GetChatGptResponse Action: This action handles the form submission when a user provides a prompt. It calls the GetChatGPTResponseAsync method, passing the user’s prompt, and then returns the API's response as a JSON object.

5. Making the API Request

private async Task<string> GetChatGPTResponseAsync(string prompt)
{
    var apiKey = ConfigurationManager.AppSettings["chatgptapiKey"].ToString();
    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);

        var requestBody = new
        {
            model = "gpt-3.5-turbo",
            messages = new[]
            {
                new { role = "system", content = "You are a helpful assistant." },
                new { role = "user", content = prompt }
            },
            max_tokens = 100
        };

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

        var response = await client.PostAsync(apiUrl, content);
        response.EnsureSuccessStatusCode();

        var responseBody = await response.Content.ReadAsStringAsync();
        dynamic result = JsonConvert.DeserializeObject(responseBody);

        return result.choices[0].message.content.ToString();
    }
}

GetChatGPTResponseAsync Method: This method performs the core functionality of sending the prompt to the ChatGPT API and returning the response.

  • API Key: The API key is retrieved from the web.config file using ConfigurationManager.AppSettings["chatgptapiKey"].
  • HttpClient: A new instance of HttpClient is used to make the POST request.
  • Request Body: The request body is constructed with the necessary parameters, including the model name, the user's prompt, and a maximum token limit.
  • Sending the Request: The request is sent asynchronously using PostAsync, and the response is processed.
  • Processing the Response: The response is deserialized, and the content of the message from the first choice is returned as a string.

6. Add View Code

<div>
    <label for="prompt">Enter your prompt:</label>
    <input type="text" id="prompt" name="prompt" />
    <button id="sendButton">Send</button>
</div>

<div id="responseContainer">
    <h3>Response:</h3>
    <p id="responseText"></p>
</div>

@section Scripts {
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#sendButton').click(function () {
                var prompt = $('#prompt').val();
                $.post('/Home/GetChatGptResponse', { prompt: prompt }, function (result) {
                    $('#responseText').text(result);
                })
             });
        });
    </script>
}

7. Run the Application

Now run the application and you will see below screen

Integrating ChatGPT API in ASPNET

Now search something here

Integrating ChatGPT API in ASPNET 2Result

Integrating ChatGPT API in ASPNET 3

Conclusion

With this setup, you now have a basic ASP.NET MVC application that can send prompts to the ChatGPT API and display the responses. This integration opens up many possibilities for creating intelligent applications powered by OpenAI's GPT models. So this is how we can integrate chatgpt api in asp.net application



 public class HomeController : Controller
 {
     private static readonly string TranslatorEndpoint = "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0";
     private static readonly string SubscriptionKey = "C5QXgp5nKcnCEVtqdADBWBo5SDoarA1ilMnRHb4BOJljBsFAdVicJQQJ99BAACGhslBXJ3w3AAAbACOGL"; // Replace with your Azure key
     private static readonly string Region = "centralindia"; // Replace with your Azure region if applicable


     protected override void OnActionExecuting(ActionExecutingContext filterContext)
     {
         string culture = (string)filterContext.RouteData.Values["lang"] ?? "en";
         Thread.CurrentThread.CurrentCulture = new CultureInfo(culture);
         Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);

         base.OnActionExecuting(filterContext);
     }
     public async Task<ActionResult> Index()
     {
      var data=   await TranslateTextAsync("Contact");
         return View();
     }
     private async Task<string> TranslateTextAsync(string text, string targetLanguage="es")
     {
         using (HttpClient client = new HttpClient())
         {
             client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", SubscriptionKey);
             client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Region", Region);

             var requestBody = new[]
             {
             new { Text = text }
         };

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

             HttpResponseMessage response = await client.PostAsync($"{TranslatorEndpoint}&to={targetLanguage}", content);
             response.EnsureSuccessStatusCode();

             string responseJson = await response.Content.ReadAsStringAsync();
             var translations = JsonConvert.DeserializeObject<dynamic>(responseJson);
             return translations[0].translations[0].text;
         }
     }
     public ActionResult About()
     {
         ViewBag.Message = "Your application description page.";

         return View();
     }

     public ActionResult Contact()
     {
         ViewBag.Message = "Your contact page.";

         return View();
     }
 }

S
Shubham Batra
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

Implement Stripe Payment Gateway In ASP.NET
Sep 10, 2020
Jquery Full Calender Integrated With ASP.NET
Sep 30, 2020
Microsoft Outlook Add Appointment and Get Appointment using Asp.Net MVC
Oct 03, 2020
How to implement JWT Token Authentication and Validate JWT Token in ASP.NET MVC using JWT
Oct 12, 2022
Previous in ASP.NET MVC
How to use Jquery Datatables in asp.net
Next in ASP.NET MVC
Translating Website Data Using Azure Translator API in ASP.NET MV…
Buy me a pizza

Comments

🔥 Trending This Month

  • 1
    Complete Guide to C++ Classes: Explained with Examples 4,212 views
  • 2
    Implementing an End-to-End CI/CD Pipeline for ASP.NET Core… 367 views
  • 3
    Create Database and CRUD operation 3,388 views
  • 4
    Mastering TypeScript Utility Types: Partial, Required, Rea… 675 views
  • 5
    Responsive Slick Slider 23,373 views
  • 6
    Integrating Azure Cognitive Search into ASP.NET Core Appli… 156 views
  • 7
    Integrating Anthropic Claude API in ASP.NET Core for AI Ch… 141 views

On this page

🎯

Interview Prep

Ace your ASP.NET MVC interview with curated Q&As for all levels.

View ASP.NET MVC Interview Q&As

More in ASP.NET MVC

  • Payumoney Integration With Asp.Net MVC 23347 views
  • MVC Crud Operation with Interfaces and Repository Pattern wi… 21996 views
  • Using Ajax in Asp.Net MVC 21349 views
  • Stopping Browser Reload On saving file in Visual Studio Asp.… 20754 views
  • Implement Stripe Payment Gateway In ASP.NET MVC 20599 views
View all ASP.NET MVC posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1770
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • ASP.NET MVC
  • ASP.NET Web Forms
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • General Web Development
  • HTML, CSS
  • HTML/CSS
  • Java
  • JavaScript
  • JavaScript, HTML, CSS
  • JavaScript, Node.js
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor