Article
Introduction
Claude (by Anthropic) is a powerful AI model you can easily integrate into your .NET Core apps for chat, content generation, and automation.
This guide shows a simple way to connect Claude using ASP.NET Core.
Step 1: Add Configuration
"ClaudeApi": {
"ApiKey": "YOUR_API_KEY",
"Endpoint": "https://api.anthropic.com/v1/messages",
"Model": "claude-sonnet-4-5",
"MaxTokens": 1024
}Step 2: Create a Service
public class ClaudeService
{
private readonly HttpClient _http;
public ClaudeService(HttpClient http)
{
_http = http;
}
public async Task<string> AskAsync(string prompt)
{
var request = new
{
model = "claude-sonnet-4-5",
max_tokens = 1024,
messages = new[]
{
new { role = "user", content = prompt }
}
};
var httpRequest = new HttpRequestMessage(HttpMethod.Post, "https://api.anthropic.com/v1/messages");
httpRequest.Headers.Add("x-api-key", "YOUR_API_KEY");
httpRequest.Headers.Add("anthropic-version", "2023-06-01");
httpRequest.Content = new StringContent(
System.Text.Json.JsonSerializer.Serialize(request),
System.Text.Encoding.UTF8,
"application/json");
var response = await _http.SendAsync(httpRequest);
var content = await response.Content.ReadAsStringAsync();
return content;
}
}Step 3: Register Service
builder.Services.AddHttpClient<ClaudeService>();Step 4: Create API Endpoint
[HttpPost("ask")]
public async Task<IActionResult> Ask([FromBody] string prompt)
{
var result = await _claudeService.AskAsync(prompt);
return Ok(result);
}Best Practices
- Store API keys securely (not in code)
- Handle errors and timeouts
- Log token usage for cost tracking
- Send conversation history for chat features
Conclusion
Integrating Claude into .NET Core is simple and powerful. With just a few steps, you can add AI features like chat, summarization, and automation to your applications.