Skip to content
Tutorials Center
My learning

Topics

Lesson 120 of 182 ยท Standard Library

HttpClient

Learn C# HttpClient: send GET and POST requests, read status codes and headers, use JSON helpers, set timeouts, reuse clients and meet IHttpClientFactory.

Almost every modern program talks to another program over HTTP: it downloads a web page, calls a payment service, asks a weather API for a forecast, or posts a log message to a server. In .NET, the class for all of this is HttpClient. It builds a request, sends it, waits for the response and gives you the status code, the headers and the body.

This lesson teaches HttpClient from the first request to the mistakes that break production systems. Because our sandbox has no internet access, every example starts a tiny web server (Kestrel, the ASP.NET Core server) on your own machine inside the same program and calls it over the loopback address 127.0.0.1. That is also a very handy technique for tests. The details of building servers come in the ASP.NET Core chapter; here, treat the server setup as scenery and focus on the client calls. You should be comfortable with async and await and with JSON first.

All HttpClient methods that talk to the network are asynchronous: they return a Task and you await them. Never call .Result or .Wait() on them. That blocks a thread and can deadlock in apps with a synchronization context.

Your first request

The smallest useful program starts a server, creates a client, sends a GET request and prints the response body. HttpClient.GetStringAsync is the shortcut for "GET this URL and give me the body as text".

C# A first GET request

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.

The ASP.NET Core namespaces (Microsoft.AspNetCore.Builder and friends) are not part of the implicit usings, so each server example begins with the using lines it needs. Three things happen in the client part. new HttpClient() creates the object that will send requests. GetStringAsync opens a TCP connection, sends GET /hello, waits for the full response and decodes the body. If the server answers with an error status such as 404 or 500, GetStringAsync throws an HttpRequestException, which is convenient for quick scripts but too blunt when you need to react to specific statuses. For that you use GetAsync.

Reading the whole response

GetAsync returns an HttpResponseMessage. It does not throw for 404 or 500: those are valid answers from a working server, so you inspect them yourself. The response has a status code, headers and content.

C# Status codes and headers

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.

The line 418 418 shows that HttpStatusCode only names the codes most programs need; unnamed codes print as plain numbers. Notice BaseAddress: once you set it, you can pass relative URLs such as "/ok". The most important members to remember are:

Member Meaning
StatusCode The HttpStatusCode enum (OK = 200, NotFound = 404, ...). Cast to int for the number.
IsSuccessStatusCode true for 200 to 299.
EnsureSuccessStatusCode() Throws HttpRequestException (with StatusCode set) for anything else.
Headers Response headers such as Server or Retry-After.
Content The body. Read it with ReadAsStringAsync, ReadAsByteArrayAsync, ReadAsStreamAsync or ReadFromJsonAsync<T>.

Both the response and the client implement IDisposable, which is why the examples use using. Disposing the response releases the connection back to the pool. See IDisposable and using for the pattern.

Sending data with POST

To send data you create an HttpContent object and pass it to PostAsync, PutAsync or PatchAsync. The content knows its own media type: StringContent for text, FormUrlEncodedContent for HTML-form style data, ByteArrayContent and StreamContent for binary data.

C# POST with text and form content

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.

The form content is percent-encoded for you: the space in Ada Lovelace becomes + and # becomes %23, exactly as the output name=Ada+Lovelace&lang=C%23 shows. That is a good reason to use the content classes instead of building strings by hand.

JSON made easy

JSON is the lingua franca of web APIs, so System.Net.Http.Json adds extension methods that combine the request, serialization and deserialization in one call: GetFromJsonAsync<T>, PostAsJsonAsync, PutAsJsonAsync and ReadFromJsonAsync<T>. They use System.Text.Json with web defaults (case-insensitive property names, camelCase output). See JSON with System.Text.Json for the serializer itself.

C# GetFromJsonAsync and PostAsJsonAsync

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.

GetFromJsonAsync calls EnsureSuccessStatusCode for you, so a 404 turns into an HttpRequestException. When the status matters (for example "404 means the item does not exist, which is fine"), use GetAsync and branch on StatusCode before you call ReadFromJsonAsync.

Headers, query strings and cancellation

Headers that belong on every request go in DefaultRequestHeaders. For one request, build an HttpRequestMessage and use SendAsync; that is also the way to use verbs such as DELETE or HEAD with custom headers. Query strings are just part of the URL, so remember to escape values with Uri.EscapeDataString.

C# Request headers and query strings

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.

If you skip the escaping, the & inside "C# & .NET" would start a new parameter and the # would cut the URL. Always escape user-provided values.

Timeouts and cancellation

A request can hang: the server is slow, the network drops packets, a firewall swallows the connection. The default HttpClient.Timeout is 100 seconds, which is far too long for most user-facing work. When the timeout expires, you get a TaskCanceledException (whose InnerException is a TimeoutException). To cancel for other reasons, pass a CancellationToken; see cancellation.

C# Timeout and cancellation

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.

You cannot change Timeout (or BaseAddress, or DefaultRequestHeaders) after the client has sent its first request: .NET throws InvalidOperationException with the message "This instance has already started one or more requests. Properties can only be modified before sending the first request." That is why the example sets the timeout in the initializer and uses a second client, patient, whose default timeout is long, for the token-based cancellation. The program prints Timed out (HttpClient.Timeout). and then Cancelled by our token..

One client, many requests

Here is the pitfall that has bitten thousands of teams: creating a new HttpClient for every request. Each client owns a connection pool. Disposing it closes the sockets, but the operating system keeps closed TCP connections in a waiting state for a while, so a busy service eventually runs out of sockets (SocketException: Address already in use). The opposite mistake exists too: a single static client that lives forever keeps resolving DNS only once per connection, so it can miss DNS changes.

The rules of thumb:

  1. In a short console program, create one HttpClient and reuse it for the whole run.
  2. In a long-running app, set PooledConnectionLifetime on a SocketsHttpHandler so connections are recycled and DNS changes are noticed.
  3. In apps that use dependency injection, ask for IHttpClientFactory or a typed client, which handles both for you.
C# A shared client with SocketsHttpHandler

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.

HttpClient is thread-safe for sending requests, so five parallel calls share the same client. Only the setup properties (BaseAddress, Timeout, DefaultRequestHeaders) must not be changed once requests are in flight.

IHttpClientFactory preview

With dependency injection (next chapter), IHttpClientFactory creates clients whose handlers are pooled and rotated for you. You register named or typed clients once and inject them anywhere. The ASP.NET Core shared framework includes it, so it runs here:

C# A typed client from IHttpClientFactory

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.

The typed client wraps the raw HTTP details behind a method named after what the caller wants. The chapter on caching and HttpClientFactory shows retries, handlers and more. In real projects you will also add a resilience library such as Polly or Microsoft.Extensions.Http.Resilience (NuGet packages, not available in our runner) for retries and circuit breakers.

Terminal
# On your machine, in a project folder (read-only, needs the dotnet CLI and NuGet):
dotnet add package Microsoft.Extensions.Http.Resilience

Common mistakes

  • New client per request. Reuse clients or use the factory.
  • Blocking on .Result. Always await.
  • Forgetting to dispose responses when you hold on to them. Disposal returns the connection to the pool.
  • Ignoring the status code. GetAsync succeeds even for 500. Check IsSuccessStatusCode or call EnsureSuccessStatusCode.
  • Reading huge bodies into memory. Pass HttpCompletionOption.ResponseHeadersRead and use ReadAsStreamAsync to stream big downloads.
  • Hard-coded secrets in code. Load tokens from configuration.
  • Trusting external input. Escape query values, and validate what you deserialize.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when you call GetAsync and the server answers 404?

    GetAsync only throws for transport problems such as connection failures. A 404 is a valid HTTP answer, so you get a response and inspect StatusCode, IsSuccessStatusCode or call EnsureSuccessStatusCode.
  2. 2. Why is creating a new HttpClient for every request a problem?

    Disposed connections linger in the operating system, so busy apps run out of sockets. Reuse one client or use IHttpClientFactory.
  3. 3. Which method sends an object as a JSON request body?

    PostAsJsonAsync serializes the object with System.Text.Json and sets the content type. GetFromJsonAsync and ReadFromJsonAsync read JSON; SendTextAsync does not exist.
  4. 4. Which exception do you get when HttpClient.Timeout expires?

    A timeout cancels the request, so you catch TaskCanceledException (an OperationCanceledException) and look at InnerException to tell it from a manual cancellation.
  5. 5. How should you put a user-typed search term into a query string?

    Characters like & and # have special meaning in URLs. Uri.EscapeDataString percent-encodes them so the value arrives intact.

Summary

  • HttpClient sends HTTP requests asynchronously; GetStringAsync is the shortest path, GetAsync and SendAsync give you the full HttpResponseMessage.
  • A non-success status does not throw by itself; use IsSuccessStatusCode or EnsureSuccessStatusCode.
  • StringContent, FormUrlEncodedContent and the JSON helpers (PostAsJsonAsync, GetFromJsonAsync, ReadFromJsonAsync) build and read bodies.
  • Set BaseAddress, DefaultRequestHeaders and Timeout before the first request; use a CancellationToken for per-call cancellation.
  • Reuse clients (or use IHttpClientFactory) instead of creating one per request, and set PooledConnectionLifetime for long-lived clients.
  • Loopback Kestrel servers make HttpClient code easy to run and test without internet access.

Next: Environment, Arguments and Process