Introduction
Large language models (LLMs) are now a normal part of application development. Anthropic's Claude is one of the most widely used models, and you can call it from any language that can send an HTTP request, including C#.
In this article, we'll build a small .NET console app that sends a question to Claude and prints the answer. No extra libraries are needed: we'll use HttpClient and System.Text.Json, which come with .NET.
Prerequisites
- .NET 8 SDK (or later) installed
- Visual Studio, VS Code or Rider
- An Anthropic API key from the Anthropic Console (console.anthropic.com)
Step 1: Create a console project
Open a terminal and run:
dotnet new console -n ClaudeDemo
cd ClaudeDemoStep 2: Store your API key safely
Never hard-code an API key in your source code. Store it in an environment variable instead.
Windows (PowerShell):
setx ANTHROPIC_API_KEY "your-api-key-here"macOS / Linux:
export ANTHROPIC_API_KEY="your-api-key-here"Restart your terminal or IDE after setting it.
Step 3: Understand the request
Claude's Messages API is a single HTTP endpoint:
- URL:
https://api.anthropic.com/v1/messages - Method: POST
- Headers:
x-api-key: your API keyanthropic-version:2023-06-01content-type:application/json
- Body: the model name, a maximum token limit, and a list of messages
Step 4: Write the code
Replace the contents of Program.cs with:
using System.Net.Http;
using System.Text;
using System.Text.Json;
var apiKey = Environment.GetEnvironmentVariable("ANTHROPIC_API_KEY")
?? throw new InvalidOperationException("Set the ANTHROPIC_API_KEY environment variable.");
using var http = new HttpClient();
http.DefaultRequestHeaders.Add("x-api-key", apiKey);
http.DefaultRequestHeaders.Add("anthropic-version", "2023-06-01");
var requestBody = new
{
model = "claude-sonnet-5-5",
max_tokens = 500,
system = "You are a helpful assistant for software testers. Keep answers short and practical.",
messages = new[]
{
new { role = "user", content = "Write 3 test cases for a login page." }
}
};
var json = JsonSerializer.Serialize(requestBody);
using var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await http.PostAsync("https://api.anthropic.com/v1/messages", content);
var responseText = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
Console.WriteLine($"Error {(int)response.StatusCode}: {responseText}");
return;
}
using var doc = JsonDocument.Parse(responseText);
var answer = doc.RootElement
.GetProperty("content")[0]
.GetProperty("text")
.GetString();
Console.WriteLine(answer);Step 5: Run it
dotnet runYou'll see Claude's answer, three test cases for a login page, printed in your console.
How the code works
systemsets Claude's role and behaviour. Here, we ask it to act as an assistant for software testers.messagesholds the conversation. Each message has arole(userorassistant) andcontent.max_tokenslimits the length of the reply, which also controls cost.- The response JSON contains a
contentarray. For a normal text reply, the answer is incontent[0].text.
Common errors and fixes
| Error | Likely cause | Fix |
|---|---|---|
| 401 Unauthorized | Missing or wrong API key | Check the environment variable is set and your IDE was restarted |
| 400 Bad Request | Invalid JSON or wrong field name | Check the model name and the messages format |
| 429 Too Many Requests | Rate limit reached | Wait and retry, ideally with exponential backoff |
Best practices
- Keep keys out of code. Use environment variables or a secrets manager.
- Use a system prompt to control tone and format.
- Set a sensible
max_tokensto control cost and response length. - Handle errors and retries in production code.
- Reuse one
HttpClient(for example viaIHttpClientFactoryin ASP.NET Core) instead of creating a new one for every request.
What to learn next
Once this works, you can explore:
- Multi-turn conversations: send previous messages back so Claude remembers context
- Streaming responses: show the answer word by word as it's generated
- Tool use: let Claude call your own C# functions
- Model Context Protocol (MCP): connect Claude to databases, files and other systems
These topics are also part of Anthropic's Claude Certified Developer – Foundations (CCDV-F) exam, if you're planning to get certified.
Conclusion
With just HttpClient and a few lines of JSON, any .NET developer can add Claude to an application. Start with a simple console app like this, then build up to chatbots, test-case generators and AI agents.

Join the conversation! Your thoughts help the community grow.