21 Calling remote APIs with IHttpClientFactory
This chapter covers
- Problems caused by using HttpClient incorrectly to call HTTP APIs
- Using IHttpClientFactory to manage HttpClient lifetimes
- Encapsulating configuration and handling transient errors with IHttpClientFactory
So far in this book we’ve focused on creating web pages and exposing APIs. Whether that’s customers browsing a Razor Pages application, or client-side SPAs and mobile apps consuming your APIs, we’ve been writing the APIs for others to consume.
However, it’s very common for your application to interact with third-party-services by consuming their APIs. For example, an eCommerce site needs to take payments, send email and SMS messages, and retrieve exchange rates from a third-party service. The most common approach for interacting with services is using HTTP. So far in this book we’ve looked at how you can expose HTTP services, using API controllers, but we haven’t looked at how you can consume HTTP services.
In section 21.1, you’ll learn the best way to interact with HTTP services using HttpClient. If you have any experience with C#, it’s very likely you’ve used this class to send HTTP requests, but there are two “gotchas” to think about, otherwise your app could run into difficulties.