Lesson 25 of 30
Working with APIs and HttpClient
C# in Visual Studio 2026 — a hands-on guide for developers at every level.
HttpClient
HttpClient is the standard way to make HTTP requests in .NET. Always reuse a single instance (or use IHttpClientFactory in real apps) to avoid socket exhaustion.
GET Request
using System.Net.Http;
using System.Net.Http.Json;
using var client = new HttpClient();
client.BaseAddress = new Uri("https://jsonplaceholder.typicode.com/");
var post = await client.GetFromJsonAsync<Post>("posts/1");
Console.WriteLine(post?.Title);
POST Request
record NewPost(string Title, string Body, int UserId);
var newPost = new NewPost("Test", "Hello API", 1);
HttpResponseMessage response = await client
.PostAsJsonAsync("posts", newPost);
response.EnsureSuccessStatusCode();
var created = await response.Content.ReadFromJsonAsync<Post>();
Console.WriteLine($"Created with ID: {created?.Id}");
Error Handling
try
{
var result = await client.GetFromJsonAsync<Post>("posts/9999");
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
{
Console.WriteLine("Post not found (404)");
}
💡 IHttpClientFactory
In ASP.NET Core or long-running apps, inject IHttpClientFactory instead of creating HttpClient directly. It manages connection lifetimes automatically.