IC Improve Code Recipes

Chapter 13

Calling Web Services

Almost every system I have worked on calls somebody else's service. A rate service at a bank, a shipping carrier's tracking API, a payroll provider, a state agency's SOAP endpoint that has not changed since 2006. These calls are where an otherwise healthy application spends most of its time waiting, and where most of its strange failures start: a timeout that hangs a page for 100 seconds, a server that runs out of sockets at noon, a retry loop that turns one slow partner into an outage.

Web service and HTTP classes turned up in 27 of the engagements in my archive, 2,696 classes in all. The pattern was the same across decades. In the early years it was a generated SOAP proxy wrapped in a ServiceHelper. Later it was WebClient, then HttpClient created and disposed on every call. Each layer worked on the developer's machine and failed under load. The archive also shows how synchronous that world was: only about 1,265 hand-written C# files (0.3%), in 11 engagements, use async/await at all. Most service calls in that code blocked a thread while they waited.

This chapter covers the recipes I now use on every project: IHttpClientFactory with typed clients, timeouts and retries through Microsoft.Extensions.Http.Resilience, a JSON client that handles errors properly, calling legacy SOAP and WCF services from modern .NET, and attaching tokens without race conditions. The packages used are Microsoft.Extensions.Http, Microsoft.Extensions.Http.Resilience, Microsoft.Extensions.Options.DataAnnotations, Microsoft.Extensions.Options.ConfigurationExtensions, System.ServiceModel.Http and System.ServiceModel.Primitives.

Recipes

  1. 13.1IHttpClientFactory and Typed ClientsYour application calls a customer API from several places. Under load it starts failing with "Only one usage of each socket address is normally…
  2. 13.2Timeouts, Retries and Circuit BreakersThe partner API is usually fast, but a few times a day it takes 40 seconds or returns a 503. Your pages hang for the full 100-second default timeout.…
  3. 13.3JSON APIs End to EndCalling a JSON API is more than one line. The request body must be serialized with the right options, errors come back as application/problem+json…
  4. 13.4Calling Legacy SOAP and WCF ServicesThe rates service, the policy-admin system or the state reporting endpoint speaks SOAP, and it is not going to change. Your new code runs on .NET 8,…
  5. 13.5Authentication Headers and TokensThe partner API wants an OAuth 2.0 bearer token from a client-credentials flow. Tokens last an hour. You need to attach a valid token to every…

Chapter checklist

  • Search for new HttpClient( inside methods and replace each with IHttpClientFactory and a typed client.
  • Give every remote service an options class, validated at start-up, with its base address and timeout.
  • Add AddStandardResilienceHandler to every outgoing client, and turn retries off for calls that are not safe to repeat.
  • Replace EnsureSuccessStatusCode with a check that keeps the server's problem details.
  • Stream large JSON responses with GetFromJsonAsAsyncEnumerable instead of buffering them.
  • Wrap every WCF call so a faulted channel is aborted, not disposed, and set MaxReceivedMessageSize on purpose.
  • Cache access tokens in a singleton and attach them in a DelegatingHandler, never by changing DefaultRequestHeaders per request.