DEV Community

Nikhil Wagh
Nikhil Wagh

Posted on

AI-Powered .NET: How to Integrate ChatGPT or Azure OpenAI in Your Web Apps (2025 Guide)

The age of AI isn't coming—it's already here. As .NET developers, integrating powerful LLMs like ChatGPT or Azure OpenAI into web apps can unlock everything from smarter customer support to AI-assisted form filling and dynamic content creation.

In this guide, we’ll walk through how to integrate ChatGPT (via Azure OpenAI) into your ASP.NET Core app step-by-step—with code examples, use cases, and best practices.

Why Integrate AI into Your .NET Apps?

  • Automate repetitive user tasks
  • Provide intelligent, conversational UI
  • Generate content dynamically
  • Enable semantic search or natural language queries
  • Build intelligent agents for internal tools

Prerequisites

  • ASP.NET Core 6+ project (e.g., Razor Pages or Web API)
  • Azure subscription with OpenAI resource deployed
  • Access to Azure OpenAI API Key
  • Basic knowledge of HTTP calls in .NET (HttpClient)

Step-by-Step Integration

1️⃣ Setup Azure OpenAI in Azure Portal

Go to Azure Portal → Create a "Azure OpenAI" resource
Deploy a model (e.g., gpt-35-turbo, gpt-4)
Grab: Endpoint, Deployment name, API key

2️⃣ Add HTTP Client in ASP.NET Core

services.AddHttpClient("AzureOpenAI", client =>
{
    client.BaseAddress = new Uri("https://<your-resource>.openai.azure.com/");
    client.DefaultRequestHeaders.Add("api-key", "<your-api-key>");
});
Enter fullscreen mode Exit fullscreen mode

3️⃣ Create Chat Request DTO

public class ChatRequest
{
    public string Role { get; set; } = "user";
    public string Content { get; set; } = string.Empty;
}
Enter fullscreen mode Exit fullscreen mode

4️⃣ Build the Chat Completion API Call

public class OpenAIService
{
    private readonly HttpClient _client;
    private readonly string _deployment = "gpt-35-turbo";

    public OpenAIService(IHttpClientFactory factory)
    {
        _client = factory.CreateClient("AzureOpenAI");
    }

    public async Task<string> GetResponseAsync(string userPrompt)
    {
        var payload = new
        {
            messages = new[]
            {
                new { role = "user", content = userPrompt }
            },
            max_tokens = 200
        };

        var response = await _client.PostAsJsonAsync(
            $"/openai/deployments/{_deployment}/chat/completions?api-version=2023-03-15-preview",
            payload);

        response.EnsureSuccessStatusCode();
        var result = await response.Content.ReadFromJsonAsync<JsonElement>();
        return result.GetProperty("choices")[0].GetProperty("message").GetProperty("content").GetString();
    }
}

Enter fullscreen mode Exit fullscreen mode

5️⃣ Create an API or Razor Page to Consume It

[ApiController]
[Route("api/chat")]
public class ChatController : ControllerBase
{
    private readonly OpenAIService _openAI;

    public ChatController(OpenAIService openAI)
    {
        _openAI = openAI;
    }

    [HttpPost]
    public async Task<IActionResult> Ask([FromBody] ChatRequest request)
    {
        var reply = await _openAI.GetResponseAsync(request.Content);
        return Ok(reply);
    }
}

Enter fullscreen mode Exit fullscreen mode

Real-World Use Cases

  • Smart Q&A Chatbots
  • AI-Powered Documentation Search
  • Dynamic Email or Report Generator
  • Intelligent Form Auto-fillers
  • Language Translation on the Fly

Security Tips

  • Always sanitize user input
  • Set token limits to avoid abuse
  • Use Rate Limiting Middleware
  • Never expose your API key on the frontend

Bonus: Logging Interactions with Serilog

Log.Information("Prompt: {Prompt}, Response: {Response}", userPrompt, response);
Enter fullscreen mode Exit fullscreen mode

Summary

The future is here—and it’s intelligent. With just a few lines of code, you can integrate advanced AI into your .NET apps and start offering game-changing experiences to your users.

What Would You Build?

Have you used AI in a .NET project yet? What’s the most exciting AI feature you want to build? Drop your thoughts in the comments

Top comments (0)