All posts
1 min read7.5k views
Engineering

How to Integrate Claude API into .NET Core

A quick guide to integrating Claude API into a .NET Core application using HttpClient and a clean service structure.

Qais Yousuf

Qais Yousuf

Software developer

April 11, 20267.5k views
How to Integrate Claude API into .NET Core

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

json
"ClaudeApi": {
  "ApiKey": "YOUR_API_KEY",
  "Endpoint": "https://api.anthropic.com/v1/messages",
  "Model": "claude-sonnet-4-5",
  "MaxTokens": 1024
}

Step 2: Create a Service

C#
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

C#
builder.Services.AddHttpClient<ClaudeService>();

Step 4: Create API Endpoint

C#
[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.

claude apidotnetaspnet coreaicsharpweb api
Share

Written by

Qais Yousuf

Qais Yousuf

Software developer

Full-Stack .NET Developer with 8+ years delivering enterprise solutions for Danish and European clients. Specialized in ASP.NET Core, Angular, and Clean Architecture, with hands-on AI integration usin