ASP.NET Core Web API Interview Question #124
How should external HTTP services be called from an ASP.NET Core Web API?
Dependency Injection, Services, EF Core, Async & Data Access Mid-Level Intermediate
Quick Interview Answer
Use IHttpClientFactory or typed/named HttpClient registrations rather than repeatedly creating and disposing HttpClient instances per request. Factory-managed clients integrate with dependency injection and provide controlled handler lifetimes and configuration.
Detailed Explanation
Use IHttpClientFactory or typed/named HttpClient registrations rather than repeatedly creating and disposing HttpClient instances per request. Factory-managed clients integrate with dependency injection and provide controlled handler lifetimes and configuration.
External calls also need explicit timeout, cancellation, error handling, and resilience strategies appropriate to the dependency.
Code Example
builder.Services.AddHttpClient<IPaymentClient, PaymentClient>(
client =>
{
client.BaseAddress = new Uri("https://payments.example.com/");
client.Timeout = TimeSpan.FromSeconds(10);
});