Tolitech.HttpClients.Abstractions provides contracts and abstractions to facilitate the creation of HTTP clients in .NET applications. It defines essential interfaces to standardize HTTP communication, making API integration simpler, safer, and more extensible.
IHttpClient: Marks classes that represent HTTP clients.IRequest: Base contract for request objects sent to HTTP endpoints.IResponse: Base contract for response objects received from HTTP endpoints.
Standardize HTTP operations, promoting reuse, testability, and consistent integration between different HTTP client implementations.
public class MyRequest : IRequest
{
public string Name { get; set; }
}
public class MyResponse : IResponse
{
public string Message { get; set; }
}Tolitech.HttpClients is a generic HTTP client implementation based on the abstractions from the previous project. It provides a powerful base class (BaseHttpClient) to perform HTTP operations (GET, POST, PUT, PATCH, DELETE) in a structured, safe, and efficient way.
- Generic implementation for HTTP clients.
- Native support for JSON (serialization/deserialization).
- Custom header management.
- HTTP response validation and error handling.
- Direct integration with Tolitech.HttpClients.Abstractions contracts.
The base class provides methods such as:
GetAsync<TResponse>(): Performs a GET request.PostAsync<TRequest, TResponse>(): Performs a POST request.PutAsync<TRequest, TResponse>(): Performs a PUT request.PatchAsync<TRequest, TResponse>(): Performs a PATCH request.DeleteAsync<TResponse>(): Performs a DELETE request.
public class MyHttpClient : BaseHttpClient
{
public MyHttpClient(HttpClient httpClient) : base(httpClient) { }
public async Task<Result<MyResponse>> GetMessageAsync(string url)
{
return await GetAsync<MyResponse>(url);
}
}HttpClient client = new HttpClient();
var service = new MyHttpClient(client);
var result = await service.GetMessageAsync("https://api.example.com/message");
if (result.IsSuccess)
{
Console.WriteLine(result.Value.Message);
}
else
{
Console.WriteLine($"Error: {result.Detail}");
}var body = new MyRequest { Name = "John" };
var headers = new Dictionary<string, string> { { "Authorization", "Bearer token" } };
var result = await service.PostAsync<MyRequest, MyResponse>(
"https://api.example.com/message",
body,
headers
);if (!result.IsSuccess)
{
Console.WriteLine($"Status: {result.StatusCode}");
Console.WriteLine($"Detail: {result.Detail}");
}The project includes unit test examples to ensure the quality and functionality of the main methods, using Moq and xUnit.
Tolitech.HttpClients.Abstractions and Tolitech.HttpClients together provide a robust, flexible, and modern solution for HTTP communication in .NET applications, promoting standardization, reuse, and ease of maintenance.