EngineeringIntermediate
How to Call a REST API in C# and .NET: HttpClient and JSON Deserialization
Direct Answer & Overview
A production .NET engineering guide for calling RESTful APIs in C# using HttpClient, IHttpClientFactory, System.Text.Json deserialization, and async/await task patterns.
1.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.
2.High-Performance JSON Serialization with System.Text.Json
Using `System.Text.Json.JsonSerializer.DeserializeAsync<T>()` streams JSON directly from the HTTP response network stream into strongly-typed C# record objects with zero unnecessary memory allocations.
3.Setting Bearer Authentication Headers
Assign authentication tokens via `client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue('Bearer', apiKey)` to ensure all outgoing requests carry valid credentials.
Invoking AI API in C# .NET 9 with HttpClientcsharp
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
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.
Can C# stream Server-Sent Events (SSE)?
Yes, using response.Content.ReadAsStreamAsync() with an IAsyncEnumerable allows real-time token streaming in C#.
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.
A100
API100 Engineering Team
Infrastructure & Latency Research

