How to Integrate Azure OpenAI Service with ASP.NET Core Web API
Integrating Azure OpenAI Service with an ASP.NET application allows you to build web-based solutions powered by OpenAI's GPT models (like GPT-3 or GPT-4) using Azure’s API. Below is an end-to-end guide on how to build an ASP.NET Core Web API application that interacts with the Azure OpenAI Service.
Prerequisites
- Azure Subscription: You need an Azure account to create an OpenAI resource.
- Azure OpenAI Resource: Create an OpenAI resource in Azure and get your API key and endpoint.
- .NET SDK: Install the .NET SDK.
- NuGet Packages: You’ll need the following NuGet packages:
Microsoft.Extensions.Configuration
Newtonsoft.Json
Microsoft.AspNetCore.Mvc.NewtonsoftJson
Step 1: Create an ASP.NET Core Web API Project
Create a new ASP.NET Core Web API project:
Step 2: Install NuGet Packages
Install the necessary NuGet packages:
Step 3: Add Configuration for Azure OpenAI in appsettings.json
In your appsettings.json
, add the configuration for your Azure OpenAI service, including the API Key, Endpoint, Deployment Name, and API Version.
Step 4: Create a Service to Call Azure OpenAI
Create a service class (OpenAIService.cs
) that will handle communication with the Azure OpenAI API.
Step 5: Register the Service in Startup.cs
or Program.cs
If you're using .NET 6 or later, register the OpenAIService
in Program.cs
:
Step 6: Create a Controller to Interact with OpenAI
Create a new controller (OpenAIController.cs
) that will expose an endpoint to interact with the OpenAI service.
Step 7: Run the Application
Build and run the ASP.NET Core Web API application:
Step 8: Test the API
Use a tool like Postman or cURL to test the API endpoint.
POST Request:
- URL:
https://localhost:5001/api/openai/ask
- Body:
{ "prompt": "What is Azure OpenAI?" }
Response:
Step 9: (Optional) Deploy to Azure
Once the application is ready, you can deploy it to Azure App Service for cloud hosting:
- Publish from Visual Studio: Right-click the project >
Publish
>Azure
. - Azure CLI Deployment: Use
dotnet publish
and deploy to an App Service.
You now have a basic ASP.NET Core Web API application integrated with Azure OpenAI Service, capable of processing natural language prompts using the OpenAI models.