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# – 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

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