Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Files and I/O

The HttpClient class

Reference for HttpClient in C#: GetStringAsync, PostAsJsonAsync, SendAsync, status codes, EnsureSuccessStatusCode, timeouts, reuse and test handlers.

HttpClient (in System.Net.Http) sends HTTP requests and receives responses. It offers convenience methods for the common cases (GetStringAsync, GetFromJsonAsync<T>, PostAsJsonAsync) and a general SendAsync(HttpRequestMessage) for full control over method, headers and content. All of them are asynchronous and return tasks.

The most important rule is to reuse the client. An HttpClient owns a connection pool; creating one per request wastes sockets and can exhaust them. Keep one instance for the lifetime of the app (a static readonly field) or obtain clients from IHttpClientFactory in ASP.NET Core and worker apps.

C#
using var client = new HttpClient { BaseAddress = new Uri("https://api.example.com/") };
string body = await client.GetStringAsync("items/1");

Try it

On this site the sandbox has no internet access, so the examples start a small web server (Kestrel) on 127.0.0.1 inside the same program and call it.

C# GET and POST against a local server

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Status codes and errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Testing without a network: a fake handler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public Task<string> GetStringAsync(string requestUri, CancellationToken cancellationToken = default);
public Task<byte[]> GetByteArrayAsync(string requestUri);
public Task<Stream> GetStreamAsync(string requestUri);
public Task<HttpResponseMessage> GetAsync(string requestUri, HttpCompletionOption completionOption);
public Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content);
public Task<HttpResponseMessage> PutAsync(string requestUri, HttpContent content);
public Task<HttpResponseMessage> DeleteAsync(string requestUri);
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request);

// System.Net.Http.Json extension methods
Task<T?> GetFromJsonAsync<T>(this HttpClient client, string requestUri);
Task<HttpResponseMessage> PostAsJsonAsync<T>(this HttpClient client, string requestUri, T value);
Name Description
BaseAddress Prefix for relative request URIs. End it with / so relative paths append instead of replacing the last segment.
DefaultRequestHeaders Headers sent with every request, such as Authorization or User-Agent.
Timeout Time limit per request (default 100 seconds).
HttpContent StringContent, ByteArrayContent, FormUrlEncodedContent, MultipartFormDataContent, StreamContent, JsonContent.
HttpCompletionOption ResponseContentRead (default) or ResponseHeadersRead, which returns as soon as headers arrive, so you can stream large bodies.

Returns: a task with the body, a stream, or an HttpResponseMessage (StatusCode, IsSuccessStatusCode, Headers, Content).

Errors: HttpRequestException for network failures, DNS errors and (via EnsureSuccessStatusCode or the Get*Async convenience methods) non-success status codes; TaskCanceledException on timeout; OperationCanceledException when you cancel; InvalidOperationException if you change properties after the first request.

Usage notes

  • Reuse one client. Do not wrap HttpClient in using per request. A shared instance reuses connections; set PooledConnectionLifetime on a SocketsHttpHandler (for example two minutes) so DNS changes are noticed. In ASP.NET Core, register clients with IHttpClientFactory.
  • Status codes are not exceptions. GetAsync, PostAsync and SendAsync return normally for 404 or 500. GetStringAsync, GetFromJsonAsync and the other convenience methods that return a body throw HttpRequestException for non-success codes. With GetAsync, check IsSuccessStatusCode or call EnsureSuccessStatusCode().
  • Dispose responses and requests. HttpRequestMessage and HttpResponseMessage hold resources. Dispose them, or read the body completely.
  • Never block on it. .Result and .Wait() on HttpClient tasks risk deadlocks in UI and legacy ASP.NET code. Use await all the way.
  • Timeouts and cancellation. The Timeout property applies to the whole request. Pass a CancellationToken for caller-driven cancellation, and check e.InnerException is TimeoutException to tell the two apart.
  • Retries belong in a handler. Use a DelegatingHandler or a resilience library to retry transient failures (5xx, timeouts) with back-off. Only retry idempotent requests.
  • Large downloads. Use GetAsync(url, HttpCompletionOption.ResponseHeadersRead) and ReadAsStreamAsync() so the body is not buffered in memory.
  • Headers. Content headers (Content-Type) live on request.Content.Headers; other headers on request.Headers. Adding a content header to the wrong collection throws InvalidOperationException.
  • Tests. Replace the HttpMessageHandler, as the last example does, instead of making real network calls.
  • The sandbox here. Only loopback addresses work on this site's runner; real hosts such as https://example.com cannot be reached.