C# – How to send synchronous requests with HttpClient

In .NET 5 and above, you can use the HttpClient Sync API methods – Send() and ReadAsStream() – to send HTTP requests synchronously (as opposed to resorting to sync-over-async). Here’s the steps for doing this: HttpClient was originally designed for async requests and has many async convenience methods (like GetAsync() and ReadAsStringAsync()). There aren’t sync … Read more

C# – How to get the status code when using HttpClient

When you use HttpClient to make requests, you can directly get the status code from the HttpResponseMessage object, like this: The main reason for checking the status code is to determine if the request was successful and then reacting to error status codes (usually by throwing an exception). The HttpResponseMessage class has two helpers that … Read more

C# – How to read problem details JSON with HttpClient

Problem details (RFC7807) is a standardized error response format that has a Content-Type of application/problem+json, an error response code (i.e. 400 – Bad Request), and has a response body that looks like this: This can be extended to include any number of properties. The example shown above comes from the default way ASP.NET Core returns … Read more

C# – Handling redirects with HttpClient

HttpClient handles redirects automatically. When you send a request, if the response contains a redirect status code (3xx) and redirect location, then it’ll send a new request to the redirect location. You can turn off this auto-redirect behavior by passing in an HttpClientHandler with AllowAutoRedirect=false. This prevents it from following redirects automatically, and allows you … Read more

C# – Examples of using JsonDocument to read JSON

You can use the JsonDocument class when you want to read and process JSON without having to deserialize the whole thing to an object. For example, let’s say you have the following JSON object representing wind variables: Now let’s say you’re only interested in the wind speed. Instead of having to deserialize this into a … Read more

C# – Configuring HttpClient connection keep-alive

When you use a single instance of HttpClient to send requests, it keeps connections open in order to speed up future requests. By default, idle connections are closed after 2 minutes, and otherwise will be kept open forever (in theory). In reality, the connection can be closed by the server-side (or other external factors) regardless … Read more

C# – The performance gains of HttpClient reusing connections

When you use the same instance of HttpClient for multiple requests (sequential and concurrent) to the same URL, it’ll reuse connections. Requests that get to reuse a connection are 5.5-8.5x faster than requests that have to open a new connection. There are a few scenarios that benefit from this connection reuse: Measuring the performance gains … Read more

C# – Disposing the request HttpContent when using HttpClient

In versions before .NET Core 3.0 (including .NET Framework), HttpClient disposes the request HttpContent object for you. This is surprising default behavior (a violation of the principle of least surprise for sure). This causes multiple problems, but one of the main problems is it prevents you from reusing the HttpContent object (you’re greeted with an … Read more

C# – How to send a file with HttpClient

In order to send a file in a request with HttpClient, add the file into a MultipartFormDataContent object, and send this object as the request content. Here’s an example: This sends the following multipart/form-data POST request: In this article, I’ll explain a few details about MultipartFormDataContent, and show a few other file-sending scenarios. MultipartFormDataContent Add() … Read more

C# – How to read response headers with HttpClient

When you send a request with HttpClient, it returns an HttpResponseMessage. You can read the response headers through the HttpResponseMessage.Headers property: This outputs the response headers: Raw response headers are really just key/value(s) pairs. When the response comes in, the headers are loaded into the Headers property (which is of type HttpResponseHeaders). This parses the … Read more

C# – How to cancel an HttpClient request

It’s a good idea to provide users with a way to cancel a HttpClient request that’s taking too long. To be able to cancel an HttpClient request, you can pass in a CancellationToken: To get a CancellationToken, you have to create a CancellationTokenSource: To actually cancel the request, you have to call CancellationTokenSource.Cancel(): This means … Read more

C# – Sending query strings with HttpClient

Query strings start with ‘?’ and have one or more key-value pairs separated by ‘&’. All characters except a-z, A-Z, 0-9 have to be encoded, including Unicode characters. When you use HttpClient, it automatically encodes the URI for you (internally, it delegates this task to the Uri class). This means when you include a query … Read more

C# – How to add request headers when using HttpClient

There are two ways add request headers when using HttpClient: In this article, I’ll show examples of both ways to add request headers. Add an unchanging header for all requests Let’s say you’re adding an API Key header. It needs to be included in all requests and the value won’t change. To add this request … Read more

C# – Circuit breaker with Polly

In an electrical system, a circuit breaker detects electrical problems and opens the circuit, which blocks electricity from flowing. To get electricity flowing again, you have to close the circuit. The same approach can be implemented in software when you’re sending requests to an external service. This is especially important when you’re sending lots of … Read more

C# – How to use Polly to do retries

Whenever you’re dealing with code that can run into transient errors, it’s a good idea to implement retries. Transient errors, by definition, are temporary and subsequent attempts should succeed. When you retry with a delay, it means you think the the transient error will go away by itself after a short period of time. When … Read more

Logging to the database with ASP.NET Core

I was reading about logging in ASP.NET when I came across this statement about logging to the database: When logging to SQL Server, don’t do so directly. Instead, add log messages to an in-memory queue and have a background worker dequeue and insert data to SQL Server. Paraphrased from Microsoft – No asynchronous logger methods … Read more

C# – How to change the HttpClient timeout per request

When you’re using the same HttpClient instance to send multiple requests, and you want to change the timeout per request, you can pass in a CancellationToken, like this: You can’t change HttpClient.Timeout after the instance has been used. You have to pass in a CancellationToken instead. There are other key points to know when trying … Read more

C# – Newtonsoft extension methods for HttpClient

System.Net.Http.Json provides extension methods that simplify getting and sending JSON with HttpClient. Internally, it uses System.Text.Json for serialization. What if you want to use Newtonsoft instead of System.Text.Json? You can use the following extension methods for that: These are modeled off of the extension methods in System.Net.Http.Json. HttpClient is used to fetch the JSON content … Read more

C# – Get and send JSON with HttpClient

The simplest way to get and send JSON with HttpClient is to use the GetFromJsonAsync() and PostAsJsonAsync() extension methods (in System.Net.Http.Json), like this: Note: You have to install the System.Net.Http.Json package if you’re using a framework version before .NET 5. These extension methods use System.Text.Json for serialization. They simplify things by abstracting away the common … Read more

C# – Switch from using HttpWebRequest to HttpClient

There are many reasons to use HttpClient instead of HttpWebRequest. For one, the MSDN docs strongly recommends against using HttpWebRequest, and using HttpClient instead. That should be enough, but if you need a little more convincing, take a look at the Practical reasons to not use HttpWebRequest section below. In addition to explaining why not … Read more

How to use toxiproxy to simulate web API error scenarios

When you have code that calls an endpoint, you need to make sure it’s resilient and can handle error scenarios, such as timeouts. One way to prove your code is resilient is by using toxiproxy to simulate bad behavior. Toxiproxy sits between your client code and the endpoint. It receives requests from your client, applies … Read more

C# – How to consume an SSE endpoint with HttpClient

Server-Sent Events (SSE) allow a client to subscribe to messages from the server. It creates a one-way stream from the server to the client. When the server has new messages for the client, it writes them to the stream. This is an alternative to the client polling the server for updates. Use the following to … Read more

C# – How to make concurrent requests with HttpClient

The HttpClient class was designed to be used concurrently. It’s thread-safe and can handle multiple requests. You can fire off multiple requests from the same thread and await all of the responses, or fire off requests from multiple threads. No matter what the scenario, HttpClient was built to handle concurrent requests. To use HttpClient effectively … Read more