Artificial intelligence is rapidly becoming a core component of modern software applications. With the release of Anthropic's Claude API, .NET developers can build intelligent chatbots, document processing systems, AI assistants, code generation tools, and enterprise automation solutions.
In this tutorial, we'll walk through the complete process of integrating Claude AI into an ASP.NET Core application using C#. You'll learn how to configure the API, create reusable services, handle requests, and expose AI functionality through REST endpoints.
Prerequisites
Before getting started, ensure you have:
.NET 8 SDK installed
Visual Studio 2022 or VS Code
Anthropic API Key
Basic understanding of ASP.NET Core Web API
NuGet Package Manager
Creating a New ASP.NET Core Project
Create a new Web API project:
dotnet new webapi -n ClaudeAIIntegration
cd ClaudeAIIntegrationRun the project:
dotnet runInstall Required Packages
Add the following packages:
dotnet add package Microsoft.Extensions.Http
dotnet add package Newtonsoft.JsonConfigure Claude API Settings
Add configuration to appsettings.json:
{
"ClaudeAI": {
"ApiKey": "YOUR_API_KEY",
"BaseUrl": "https://api.anthropic.com/v1/messages",
"Model": "claude-sonnet-4-0"
}
}Create a configuration model:
public class ClaudeSettings
{
public string ApiKey { get; set; }
public string BaseUrl { get; set; }
public string Model { get; set; }
}Create Request Models
ClaudeRequest.cs
public class ClaudeRequest
{
public string Prompt { get; set; }
}ClaudeResponse.cs
public class ClaudeResponse
{
public string Content { get; set; }
}Build Claude AI Service
Create Services/ClaudeService.cs
using System.Text;
using Newtonsoft.Json;
public class ClaudeService
{
private readonly HttpClient _httpClient;
private readonly IConfiguration _configuration;
public ClaudeService(
HttpClient httpClient,
IConfiguration configuration)
{
_httpClient = httpClient;
_configuration = configuration;
}
public async Task<string> GetResponseAsync(string prompt)
{
var apiKey = _configuration["ClaudeAI:ApiKey"];
var model = _configuration["ClaudeAI:Model"];
var endpoint = _configuration["ClaudeAI:BaseUrl"];
_httpClient.DefaultRequestHeaders.Clear();
_httpClient.DefaultRequestHeaders.Add(
"x-api-key",
apiKey);
_httpClient.DefaultRequestHeaders.Add(
"anthropic-version",
"2023-06-01");
var requestBody = new
{
model = model,
max_tokens = 1024,
messages = new[]
{
new
{
role = "user",
content = prompt
}
}
};
var json =
JsonConvert.SerializeObject(requestBody);
var content =
new StringContent(
json,
Encoding.UTF8,
"application/json");
var response =
await _httpClient.PostAsync(
endpoint,
content);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
Join the conversation! Your thoughts help the community grow.