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.
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.
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.
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.
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
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
HttpClientinusingper request. A shared instance reuses connections; setPooledConnectionLifetimeon aSocketsHttpHandler(for example two minutes) so DNS changes are noticed. In ASP.NET Core, register clients withIHttpClientFactory. - Status codes are not exceptions.
GetAsync,PostAsyncandSendAsyncreturn normally for 404 or 500.GetStringAsync,GetFromJsonAsyncand the other convenience methods that return a body throwHttpRequestExceptionfor non-success codes. WithGetAsync, checkIsSuccessStatusCodeor callEnsureSuccessStatusCode(). - Dispose responses and requests.
HttpRequestMessageandHttpResponseMessagehold resources. Dispose them, or read the body completely. - Never block on it.
.Resultand.Wait()on HttpClient tasks risk deadlocks in UI and legacy ASP.NET code. Useawaitall the way. - Timeouts and cancellation. The
Timeoutproperty applies to the whole request. Pass aCancellationTokenfor caller-driven cancellation, and checke.InnerException is TimeoutExceptionto tell the two apart. - Retries belong in a handler. Use a
DelegatingHandleror a resilience library to retry transient failures (5xx, timeouts) with back-off. Only retry idempotent requests. - Large downloads. Use
GetAsync(url, HttpCompletionOption.ResponseHeadersRead)andReadAsStreamAsync()so the body is not buffered in memory. - Headers. Content headers (
Content-Type) live onrequest.Content.Headers; other headers onrequest.Headers. Adding a content header to the wrong collection throwsInvalidOperationException. - 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.comcannot be reached.