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 e-commerce 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.

21.1 Calling HTTP APIs: The problem with HttpClient

 

21.2 Creating HttpClients with IHttpClientFactory

 
 
 
 

21.2.1 Using IHttpClientFactory to manage HttpClientHandler lifetime

 

21.2.2 Configuring named clients at registration time

 

21.2.3 Using typed clients to encapsulate HTTP calls

 
 
 

21.3 Handling transient HTTP errors with Polly

 
 

21.4 Creating a custom HttpMessageHandler

 
 
 

Summary

 
 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest