Claude API C# .NET Tutorial: Complete Integration Guide (2026)
You can call the Claude API from C# .NET using the official Anthropic NuGet package — install with dotnet add package Anthropic.SDK, set your ANTHROPIC_API_KEY, and send messages in under 15 lines of code. The SDK supports .NET 6+, streaming, tool use, prompt caching, and multi-turn conversations. This tutorial walks through setup, authentication, every major feature, and production patterns with tested code examples.
Installation and Setup
Create a new project or add the SDK to an existing one:
dotnet new console -n ClaudeDemo
cd ClaudeDemo
dotnet add package Anthropic.SDK
Set your API key as an environment variable:
# Linux/macOS
export ANTHROPIC_API_KEY="sk-ant-..."
# Windows PowerShell
$env:ANTHROPIC_API_KEY = "sk-ant-..."
Or store it in appsettings.json for ASP.NET Core projects:
{
"Anthropic": {
"ApiKey": "sk-ant-..."
}
}
Security note: Never hardcode API keys in source files. Use environment variables, user secrets (dotnet user-secrets), or Azure Key Vault in production.
Your First API Call
using Anthropic.SDK;
using Anthropic.SDK.Messaging;
var client = new AnthropicClient();
var message = await client.Messages.CreateAsync(new MessageParameters
{
Model = "claude-sonnet-4-5",
MaxTokens = 1024,
Messages = new List<Message>
{
new Message(RoleType.User, "Explain dependency injection in C# in one paragraph.")
}
});
Console.WriteLine(message.Content[0].Text);
The client reads ANTHROPIC_API_KEY from your environment automatically. No additional configuration is needed for basic usage.
Understanding the Response
Console.WriteLine($"Message ID: {message.Id}");
Console.WriteLine($"Model: {message.Model}");
Console.WriteLine($"Stop Reason: {message.StopReason}");
Console.WriteLine($"Input Tokens: {message.Usage.InputTokens}");
Console.WriteLine($"Output Tokens: {message.Usage.OutputTokens}");
Console.WriteLine($"Response: {message.Content[0].Text}");
Track Usage.InputTokens and Usage.OutputTokens for cost monitoring. Multiply by the per-token rate for your model. See Claude API Cost and Prompt Caching Break-Even for current pricing tables.
System Prompts
var message = await client.Messages.CreateAsync(new MessageParameters
{
Model = "claude-sonnet-4-5",
MaxTokens = 1024,
SystemMessage = "You are a senior C# developer. Answer concisely with code examples. Use modern C# syntax.",
Messages = new List<Message>
{
new Message(RoleType.User, "How do I implement the repository pattern with EF Core?")
}
});
System prompts persist across multi-turn conversations. Put your role instructions, output format requirements, and constraints here.
Streaming Responses
For real-time output in chat UIs or long-running tasks:
var parameters = new MessageParameters
{
Model = "claude-sonnet-4-5",
MaxTokens = 2048,
Messages = new List<Message>
{
new Message(RoleType.User, "Write a complete CRUD controller for a Product entity in ASP.NET Core.")
},
Stream = true
};
await foreach (var evt in client.Messages.CreateStreamAsync(parameters))
{
if (evt is ContentBlockDelta delta)
{
Console.Write(delta.Delta?.Text);
}
}
Performance benchmark: First token arrives in 300-500ms with streaming. Without streaming, a 2,000-token response takes 5-12 seconds for the full payload. For any user-facing application, streaming is strongly recommended.
Build production-ready Claude integrations
Agent SDK Cookbook ($49) includes 30+ production recipes: streaming pipelines, multi-agent coordination, tool use chains, error handling, and cost optimization patterns — applicable to any language including C#.
Multi-Turn Conversations
Build conversation history by tracking messages:
var conversation = new List<Message>();
async Task<string> ChatAsync(string userMessage)
{
conversation.Add(new Message(RoleType.User, userMessage));
var response = await client.Messages.CreateAsync(new MessageParameters
{
Model = "claude-sonnet-4-5",
MaxTokens = 1024,
Messages = conversation
});
var assistantText = response.Content[0].Text;
conversation.Add(new Message(RoleType.Assistant, assistantText));
return assistantText;
}
Console.WriteLine(await ChatAsync("What is the difference between abstract classes and interfaces in C#?"));
Console.WriteLine(await ChatAsync("When should I prefer one over the other?"));
Console.WriteLine(await ChatAsync("Show me a code example using both together."));
Claude has no persistent memory across requests. You manage context by passing the full conversation history each time.
ASP.NET Core Dependency Injection
Register the client as a singleton in Program.cs:
builder.Services.AddSingleton<AnthropicClient>(sp =>
{
var apiKey = builder.Configuration["Anthropic:ApiKey"];
return new AnthropicClient(apiKey);
});
Inject it into your controllers or services:
[ApiController]
[Route("api/[controller]")]
public class ChatController : ControllerBase
{
private readonly AnthropicClient _client;
public ChatController(AnthropicClient client)
{
_client = client;
}
[HttpPost]
public async Task<IActionResult> Chat([FromBody] ChatRequest request)
{
var response = await _client.Messages.CreateAsync(new MessageParameters
{
Model = "claude-sonnet-4-5",
MaxTokens = 1024,
Messages = new List<Message>
{
new Message(RoleType.User, request.Message)
}
});
return Ok(new { response = response.Content[0].Text });
}
}
Tool Use (Function Calling)
Define tools so Claude can call your C# methods:
var tools = new List<Tool>
{
new Tool
{
Name = "get_weather",
Description = "Get current weather for a city",
InputSchema = new InputSchema
{
Type = "object",
Properties = new Dictionary<string, Property>
{
["city"] = new Property { Type = "string", Description = "City name" }
},
Required = new[] { "city" }
}
}
};
var response = await client.Messages.CreateAsync(new MessageParameters
{
Model = "claude-sonnet-4-5",
MaxTokens = 1024,
Tools = tools,
Messages = new List<Message>
{
new Message(RoleType.User, "What's the weather in Seoul?")
}
});
if (response.StopReason == "tool_use")
{
var toolCall = response.Content.OfType<ToolUseContent>().First();
Console.WriteLine($"Tool: {toolCall.Name}, Input: {toolCall.Input}");
// Execute your function and return result to Claude
}
For deeper tool use patterns and multi-agent architectures, see the Claude Agent SDK Guide.
Error Handling and Retry Logic
using Polly;
using Polly.Retry;
var retryPolicy = Policy
.Handle<HttpRequestException>()
.Or<AnthropicApiException>(ex => ex.StatusCode == 429)
.WaitAndRetryAsync(3, attempt => TimeSpan.FromSeconds(Math.Pow(2, attempt)));
var response = await retryPolicy.ExecuteAsync(async () =>
{
return await client.Messages.CreateAsync(new MessageParameters
{
Model = "claude-sonnet-4-5",
MaxTokens = 1024,
Messages = new List<Message>
{
new Message(RoleType.User, "Hello from C#!")
}
});
});
Use Polly for production-grade retry policies. Rate limit errors (429) should always use exponential backoff.
Model Selection in C#
// Best balance of capability and cost
var model = "claude-sonnet-4-5";
// Simple, high-volume tasks (10x cheaper)
var model = "claude-haiku-4-5";
// Complex reasoning, architecture decisions (3x more expensive)
var model = "claude-opus-4-5";
Cost data point: A .NET microservices project processing 10,000 API calls/day reduced monthly costs by 62% by routing simple classification tasks to Haiku and reserving Sonnet for code generation. See Claude Haiku vs Sonnet vs Opus: Which Model for detailed benchmarks.
Frequently Asked Questions
Does the Claude API have an official C# SDK?
The Anthropic.SDK NuGet package is the community-maintained C# SDK, widely used in production. It covers all API features: messages, streaming, tool use, and prompt caching. Install with dotnet add package Anthropic.SDK. You can also call the REST API directly with HttpClient if you prefer no dependencies.
What .NET versions are supported?
The SDK targets .NET Standard 2.0, meaning it works with .NET 6, .NET 7, .NET 8, and .NET Framework 4.7.2+. For best performance and modern C# features (async streams, records), use .NET 8 or later.
How do I use Claude with Azure Functions?
Register the AnthropicClient in your Program.cs using dependency injection, the same way as ASP.NET Core. Set the API key via Azure Application Settings (environment variables). The client is thread-safe and can be registered as a singleton.
Is the C# client thread-safe?
Yes. The AnthropicClient uses HttpClient internally and is safe to share across threads. Register it as a singleton in your DI container — do not create a new instance per request.
How do I handle token limits in C#?
Check response.Usage.InputTokens and response.Usage.OutputTokens after each call. For pre-flight token estimation, use the token counting endpoint before sending large prompts. The Claude API Cost guide explains token pricing in detail.
Can I use Claude with Blazor applications?
Yes. For Blazor Server, inject AnthropicClient through DI and call it directly. For Blazor WebAssembly, route requests through a server-side API endpoint — never expose your API key in client-side code.
30+ production recipes for Claude API
Agent SDK Cookbook ($49) covers streaming pipelines, multi-agent coordination, tool use chains, error recovery, and cost optimization — patterns that apply directly to C# .NET projects.