How to Call a REST API in C# and .NET: HttpClient and JSON Deserialization
A production .NET engineering guide for calling RESTful APIs in C# using HttpClient, IHttpClientFactory, System.Text.Json deserialization, and async/await task patterns.
Overview #
A production .NET engineering guide for calling RESTful APIs in C# using HttpClient, IHttpClientFactory, System.Text.Json deserialization, and async/await task patterns.
The HttpClient Socket Exhaustion Trap in C# #
A classic mistake in C# is wrapping HttpClient in a using statement for each request. Even after disposal, underlying TCP sockets linger in TIME_WAIT state, leading to socket exhaustion under heavy load. In production .NET 8/9 applications, always use IHttpClientFactory or a static singleton HttpClient instance.
High-Performance JSON Serialization with System.Text.Json #
Using System.Text.Json.JsonSerializer.DeserializeAsync streams JSON directly from the HTTP response network stream into strongly-typed C# record objects with zero unnecessary memory allocations.
Setting Bearer Authentication Headers #
Assign authentication tokens via client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue('Bearer', apiKey) to ensure all outgoing requests carry valid credentials.
Code Example: Invoking AI API in C# .NET 9 with HttpClient #
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
class Program
{
private static readonly HttpClient client = new HttpClient();
static async Task Main()
{
client.BaseAddress = new Uri("https://api.apihundred.com/v1/");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "your_api_key");
var payload = new
{
model = "gpt-6-sol",
messages = new[] { new { role = "user", content = "Explain async in C# in 2 sentences." } }
};
var json = JsonSerializer.Serialize(payload);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync("chat/completions", content);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine($"C# Response: {responseBody}");
}
}
Frequently Asked Questions #
Q: Why should I use IHttpClientFactory in ASP.NET Core?
IHttpClientFactory manages the lifetime of underlying HttpMessageHandler instances to prevent socket exhaustion and automatically handle DNS changes.
Q: Can C# stream Server-Sent Events (SSE)?
Yes, using response.Content.ReadAsStreamAsync() with an IAsyncEnumerable allows real-time token streaming in C#.
Q: Is there an official OpenAI SDK for C# / .NET?
Yes, Microsoft and OpenAI maintain the official OpenAI .NET library, which can point directly to API100 by setting Endpoint.
Build with API100
Access 100+ AI models through one lightning-fast OpenAI-compatible API with sub-50ms routing overhead and zero markup on cached tokens.

