Tutorials ASP.NET Core Complete Tutorial (ShopNest)

HTTP Client and Consuming External APIs in ASP.NET Core

Learn HTTP Client and Consuming External APIs in ASP.NET Core in our free ASP.NET Core Complete Tutorial (ShopNest) series. Step-by-step explanations, examples, and interview tips on Toolliyo Academy.

On this page
HTTP Client and Consuming External APIs in ASP.NET Core — ShopNest
Article 41 of 75 · Module 5: Web API · ShopNest Weather Integration App
Target keyword: httpclient asp.net core · Read time: ~29 min · .NET: 8 / 9 · Project: ShopNest Weather Integration App

Introduction

ShopNest Weather widget calls OpenWeather API — never new HttpClient() per request (socket exhaustion). Use IHttpClientFactory with typed clients and Polly resilience.

After this article you will

  • Register typed HttpClient with IHttpClientFactory
  • Deserialize JSON with System.Text.Json
  • Add retry, timeout, and circuit breaker
  • Pass API keys via configuration securely
  • Mock HttpClient in unit tests

Prerequisites

Concept deep-dive

public interface IWeatherClient
{
    Task<WeatherDto?> GetCurrentAsync(string city, CancellationToken ct = default);
}

public class OpenWeatherClient : IWeatherClient
{
    private readonly HttpClient _http;
    public OpenWeatherClient(HttpClient http, IOptions<WeatherOptions> options)
    {
        _http = http;
        _http.BaseAddress = new Uri("https://api.openweathermap.org/data/2.5/");
    }
    public async Task<WeatherDto?> GetCurrentAsync(string city, CancellationToken ct)
    {
        var response = await _http.GetAsync($"weather?q={Uri.EscapeDataString(city)}&appid=...", ct);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadFromJsonAsync<WeatherDto>(cancellationToken: ct);
    }
}

builder.Services.AddHttpClient<IWeatherClient, OpenWeatherClient>(client =>
{
    client.Timeout = TimeSpan.FromSeconds(10);
})
.AddStandardResilienceHandler(); // .NET 8 Polly integration

Hands-on — ShopNest Weather Integration App

  1. WeatherOptions with ApiKey in User Secrets.
  2. WeatherController returns cached forecast for ShopNest homepage.
  3. Simulate 503 — verify retry then circuit opens.
  4. Unit test with MockHttpMessageHandler.

Common errors & best practices

  • new HttpClient() in using block per call — DNS/socket issues under load.
  • API key in query string logged — prefer header where provider allows.
  • No timeout — hung threads block request pool.

Interview questions

Q: Why IHttpClientFactory?
A: Manages HttpClient lifetime and handler rotation — avoids socket exhaustion.

Q: Typed vs named client?
A: Typed binds interface to implementation; named uses string key — typed is cleaner.

Q: Circuit breaker?
A: Stops calling failing external API temporarily — fail fast protects ShopNest.

Summary

  • IHttpClientFactory is the correct HttpClient pattern
  • Typed clients + options for OpenWeather integration
  • Resilience handlers add retry and circuit breaker
  • Mock handlers enable fast unit tests without network

Previous: Pagination, Filtering and Sorting
Next: Minimal APIs

FAQ

Polly vs StandardResilienceHandler?

.NET 8 Microsoft.Extensions.Http.Resilience wraps Polly — prefer for new apps.

Cache external API responses?

IMemoryCache with TTL reduces rate limits and latency.

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

ASP.NET Core Complete Tutorial (ShopNest)
Course syllabus
Module 1: Foundations
Module 2: Entity Framework Core
Module 3: Dependency Injection & Middleware
Module 4: Authentication & Security
Module 5: Web API
Module 6: Advanced Architecture
Module 7: Testing
Module 8: Deployment & DevOps
Module 9: Real-World Projects
Module 10: Advanced Topics
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details