Consuming APIs in ASP.NET Core MVC
In today’s interconnected world, modern web applications rarely operate in isolation. They often need to communicate with external services to fetch data, send updates, or integrate with third-party systems. Whether you’re displaying weather information, processing payments, or connecting to your company’s microservices, learning how to consume APIs in ASP.NET Core MVC is an essential skill.
ASP.NET Core:
It provides a robust and efficient way to make HTTP requests using HttpClient, which lives in the System.Net.Http namespace. However, directly instantiating HttpClient inside controllers or services can lead to issues like socket exhaustion if not managed properly. That’s why the recommended approach in ASP.NET Core is to use IHttpClientFactory, introduced in .NET Core 2.1, which helps create and manage HttpClient instances efficiently.
To get started, register IHttpClientFactory in your Startup.cs or Program.cs (depending on your project setup) by calling:
builder.Services.AddHttpClient();
This makes IHttpClientFactory available through dependency injection across your application. In your controller or service class, you inject the factory:
csharp
Copy
Edit
public class WeatherController : Controller
{
private readonly HttpClient _httpClient;
public WeatherController(IHttpClientFactory httpClientFactory)
{
_httpClient = httpClientFactory.CreateClient();
}
public async Task<IActionResult> Index()
{
try
{
var response = await _httpClient.GetAsync("https://api.example.com/weather/today");
if (response.IsSuccessStatusCode)
{
var jsonData = await response.Content.ReadAsStringAsync();
var weatherData = JsonSerializer.Deserialize<WeatherViewModel>(jsonData);
return View(weatherData);
}
else
{
// Log error, show friendly message
ViewBag.Error = $"API Error: {response.StatusCode}";
return View("Error");
}
}
catch (Exception ex)
{
// Log exception details
ViewBag.Error = $"Exception: {ex.Message}";
return View("Error");
}
}
}
In this example, we use GetAsync() to call the external API. The response is read asynchronously with ReadAsStringAsync() and deserialized using System.Text.Json.JsonSerializer into a strongly-typed view model. This allows you to pass data directly to your Razor view and display it elegantly.
Why IHttpClientFactory?
Using IHttpClientFactory offers benefits like:
- Lifetime management: Prevents socket exhaustion by reusing connections properly.
- Configuration: Allows defining named or typed clients with default settings like base URLs, headers, or timeouts.
- Resilience: Makes it easy to integrate libraries like Polly for retries, timeouts, or circuit breaker patterns.
For example, configuring a named client in Program.cs:
builder.Services.AddHttpClient("WeatherApi", client =>
{
client.BaseAddress = new Uri("https://api.example.com/");
client.DefaultRequestHeaders.Add("Accept", "application/json");
client.Timeout = TimeSpan.FromSeconds(30);
});
And using it in your controller:
_httpClient = httpClientFactory.CreateClient("WeatherApi");
var response = await _httpClient.GetAsync("weather/today");
This approach centralizes configuration, making it easier to manage changes and maintain consistency across your application.
Tips for best practices:
Always check IsSuccessStatusCode to handle failures gracefully.
Use strongly-typed models for deserialization instead of dynamic objects for better maintainability.
Add proper error logging for failed requests or exceptions.
Secure sensitive API keys with user secrets or environment variables instead of hardcoding them.
Conclusion:
By mastering API consumption with HttpClient and IHttpClientFactory, you’ll unlock the ability to build powerful ASP.NET Core MVC applications that can integrate seamlessly with virtually any RESTful API, providing dynamic, real-time data and richer user experiences.
Learn Fullstack .Net Training Course
Read More:
Using Dependency Injection in ASP.NET Core
Authentication and Authorization in ASP.NET
Building a Web API from Scratch
Visit Quality Thought Training Institute
Comments
Post a Comment