HttpClient and Dependency Injection (DI)
.NET 8 (Web Application)
Using the built-in Dependency Injection (DI) framework.
Program.cs
var builder = WebApplication.CreateBuilder(args);
// Register HttpClient with DI
builder.Services.AddHttpClient<IProductService, ProductService>();
var app = builder.Build();
// Your middleware and routing setup here
app.Run();Define an interface for your service and an implementation that uses HttpClient.
IProductService.cs
public interface IProductService
{
Task<Product> GetProductAsync(int id);
}ProductService.cs
using System.Net.Http;
using System.Net.Http.Json;
public class ProductService : IProductService
{
private readonly HttpClient _httpClient;
public ProductService(HttpClient httpClient)
{
_httpClient = httpClient;
}
/*
Key Features:
* Simplicity: This method is concise and straightforward. It utilizes the GetFromJsonAsync<T> extension method provided by System.Net.Http.Json, which handles both the HTTP GET request and the deserialization of the JSON response into the specified type (Product)
* Automatic Handling: It automatically returns null if the response is unsuccessful (e.g., 404 Not Found), without throwing an exception.
* Less Control: Since it abstracts away the lower-level details, you have less control over error handling and logging.
*/
public async Task<Product> GetProductAsync(int id)
{
return await _httpClient.GetFromJsonAsync<Product>($"https://api.example.com/products/{id}");
}
// Manual Deserialization, Custom Error Handling
// More flexible, allowing developers to implement specific error handling and logging strategies.
public async Task<List<Product>> GetProductsAsync()
{
var response = await _httpClient.GetAsync("https://api.example.com/products");
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
var products = JsonSerializer.Deserialize<List<Products>>(body);
return products ?? throw new MissingProductsException();
}
}Product.cs
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}ASP.NET Framework
Links: