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

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. You can pass in a JsonSerializerSettings object to … Read more