33 Calling remote APIs with IHttpClientFactory

 

This chapter covers

  • Seeing 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 common for your application to interact with third-party services by consuming their APIs as well as your own API apps. For example, an e-commerce site needs to take payments, send email and Short Message Service (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 minimal APIs and API controllers, but we haven’t looked at how you can consume HTTP services.

In section 33.1 you’ll learn the best way to interact with HTTP services using HttpClient. If you have any experience with C#, it’s likely that you’ve used this class to send HTTP requests, but there are two gotchas to think about; otherwise, your app could run into difficulties.

33.1 Calling HTTP APIs: The problem with HttpClient

33.2 Creating HttpClients with IHttpClientFactory

33.2.1 Using IHttpClientFactory to manage HttpClientHandler lifetime

33.2.2 Configuring named clients at registration time

33.2.3 Using typed clients to encapsulate HTTP calls

33.3 Handling transient HTTP errors with Polly

33.4 Creating a custom HttpMessageHandler

Summary