Nosabit.Adapters.Persistence.HttpClientExtension 1.2.0

dotnet add package Nosabit.Adapters.Persistence.HttpClientExtension --version 1.2.0
                    
NuGet\Install-Package Nosabit.Adapters.Persistence.HttpClientExtension -Version 1.2.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Nosabit.Adapters.Persistence.HttpClientExtension" Version="1.2.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Nosabit.Adapters.Persistence.HttpClientExtension" Version="1.2.0" />
                    
Directory.Packages.props
<PackageReference Include="Nosabit.Adapters.Persistence.HttpClientExtension" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Nosabit.Adapters.Persistence.HttpClientExtension --version 1.2.0
                    
#r "nuget: Nosabit.Adapters.Persistence.HttpClientExtension, 1.2.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#addin nuget:?package=Nosabit.Adapters.Persistence.HttpClientExtension&version=1.2.0
                    
Install Nosabit.Adapters.Persistence.HttpClientExtension as a Cake Addin
#tool nuget:?package=Nosabit.Adapters.Persistence.HttpClientExtension&version=1.2.0
                    
Install Nosabit.Adapters.Persistence.HttpClientExtension as a Cake Tool

Nosabit.Adapters.Persistence.HttpClientExtension

Colección de extensiones para HttpClient que facilita la comunicación con APIs REST y servicios SOAP en aplicaciones .NET. Proporciona métodos tipados para operaciones HTTP comunes con manejo de serialización/deserialización automática.

NuGet License: MIT

Instalación

Package Manager

Install-Package Nosabit.Adapters.Persistence.HttpClientExtension

.NET CLI

dotnet add package Nosabit.Adapters.Persistence.HttpClientExtension

Características principales

  • Métodos HTTP tipados: Extensiones para GET, POST, PUT y DELETE con tipos genéricos
  • Serialización/deserialización automática: Manejo transparente de JSON utilizando System.Text.Json
  • Soporte para XML: Métodos para trabajar con contenido XML y SOAP
  • Procesamiento de DataSet: Conversión directa de respuestas a DataSet
  • Manejo de errores consistente: Todos los métodos incluyen validación de códigos de estado HTTP
  • API fluida: Diseño intuitivo para encadenar operaciones
  • Fuertemente tipado: Aprovecha las características genéricas de C# para máxima seguridad de tipos

Ejemplos de uso

Operaciones REST básicas

// Configurar el HttpClient
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://api.example.com/");

// GET tipado
var product = await client.Fetch_GetAsync<ProductDto>("products/1");

// POST con envío de objeto y recepción de tipo específico
var createdOrder = await client.Fetch_PostAsync<OrderResponseDto>("orders", orderRequest);

// PUT con objeto de envío y tipo de respuesta específico
var updatedUser = await client.Fetch_PutAsync<UserDto>("users/1", userToUpdate);

// DELETE tipado
var deletionResult = await client.Fetch_DeleteAsync<DeletionResultDto>("products/1");

Trabajando con contenido XML

// Obtener XML como XDocument
XDocument xmlDoc = await client.Fetch_GetXMLAsync("api/data");

// Obtener XML como DataSet
DataSet dataSet = await client.Fetch_GetXMLDataSet("api/dataset");

// Enviar JSON y recibir XML como DataSet
var requestData = new { id = 123, name = "Test" };
DataSet resultDataSet = await client.Fetch_PostXMLDataSet("api/convert", requestData);

Operaciones SOAP

// Petición SOAP simple
DataSet soapResult = await client.Fetch_SendSoapPostAsync("https://soap.example.com/service");

// Petición SOAP con cuerpo personalizado
string soapEnvelope = @"
<soap:Envelope xmlns:soap=""http://www.w3.org/2003/05/soap-envelope"">
  <soap:Body>
    <GetStockPrice xmlns=""http://example.com/"">
      <StockName>MSFT</StockName>
    </GetStockPrice>
  </soap:Body>
</soap:Envelope>";

DataSet soapResponse = await client.Fetch_SendSoapPostAsync(
    "https://soap.example.com/service", 
    soapEnvelope
);

Manejo de formularios

// Crear formulario
var formContent = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("username", "user123"),
    new KeyValuePair<string, string>("password", "pass456")
});

// Enviar formulario y recibir respuesta tipada
var loginResult = await client.Fetch_PostFormAsync<LoginResponseDto>(
    "auth/login", 
    formContent
);

Obtener respuesta como cadena

// GET que devuelve una cadena
string htmlContent = await client.Fetch_GetStringAsync("https://example.com");

// POST que devuelve una cadena
var requestData = new { query = "search term" };
string searchResults = await client.Fetch_PostStringAsync("api/search", requestData);

Métodos disponibles

GET

  • Fetch_GetAsync<T>: Obtiene y deserializa automáticamente a tipo T
  • Fetch_GetStringAsync: Obtiene el contenido como string
  • Fetch_GetXMLAsync: Obtiene y parsea el contenido como XDocument
  • Fetch_GetXMLDataSet: Obtiene y convierte el contenido a DataSet

POST

  • Fetch_PostAsync<T>(string url): POST simple que devuelve un objeto de tipo T
  • Fetch_PostAsync<TResult>(string url, object val): POST con tipo genérico para la respuesta y objeto para el envío
  • Fetch_PostAsync<TResult>(string url, HttpContent val): POST con contenido HTTP personalizado
  • Fetch_PostFormAsync<TResult>(string url, FormUrlEncodedContent val): POST para formularios codificados en URL
  • Fetch_PostSerializeAsync<TResult>(string url): POST sin cuerpo que devuelve objeto tipado
  • Fetch_PostSerializeAsync<TResult>(string url, object val): POST con serialización manual del objeto
  • Fetch_PostStringAsync<TSend>(string url, object val): POST que devuelve una cadena
  • Fetch_PostXMLDataSet<TSend>(string url, TSend val): POST que devuelve XML como DataSet

PUT

  • Fetch_PutAsync<T>(string url): PUT simple que devuelve un objeto de tipo T
  • Fetch_PutAsync<TResult>(string url, object val): PUT con tipo genérico para la respuesta y objeto para el envío

DELETE

  • Fetch_DeleteAsync<T>: DELETE que devuelve un objeto de tipo T

SOAP

  • Fetch_SendSoapPostAsync(string): Petición SOAP simple
  • Fetch_SendSoapPostAsync(string, string): Petición SOAP con cuerpo personalizado

Manejo de errores

Todos los métodos incluyen manejo de errores consistente. Si la respuesta HTTP no es exitosa (código de estado no está en el rango 200-299), se lanzará una excepción con el mensaje de error y el contenido de la respuesta:

try
{
    var data = await client.Fetch_GetAsync<MyDataType>("api/data");
    // Procesar datos...
}
catch (Exception ex)
{
    // El mensaje de excepción contiene el código de estado HTTP y el contenido de la respuesta
    Console.WriteLine($"Error al obtener datos: {ex.Message}");
}

Mejores prácticas

  1. Usar tipos específicos: Define clases DTO para request y response en lugar de usar tipos dinámicos.
  2. Reutilizar HttpClient: Crea una sola instancia de HttpClient para toda la aplicación.
  3. Configurar tiempos de espera: Establece tiempos de espera adecuados para evitar bloqueos.
  4. Manejar excepciones: Implementa manejo de errores para todas las llamadas HTTP.
  5. Evitar bloqueo del hilo principal: Usa siempre los métodos asincrónicos en código asincrónico.

Ejemplo de servicio completo

public class ProductApiService
{
    private readonly HttpClient _httpClient;
    
    public ProductApiService(HttpClient httpClient)
    {
        _httpClient = httpClient;
        _httpClient.BaseAddress = new Uri("https://api.example.com/");
    }
    
    public async Task<List<ProductDto>> GetAllProductsAsync()
    {
        return await _httpClient.Fetch_GetAsync<List<ProductDto>>("products");
    }
    
    public async Task<ProductDto> GetProductByIdAsync(int id)
    {
        return await _httpClient.Fetch_GetAsync<ProductDto>($"products/{id}");
    }
    
    public async Task<ProductDto> CreateProductAsync(CreateProductDto productDto)
    {
        return await _httpClient.Fetch_PostAsync<ProductDto>("products", productDto);
    }
    
    public async Task<ProductDto> UpdateProductAsync(int id, UpdateProductDto productDto)
    {
        return await _httpClient.Fetch_PutAsync<ProductDto>($"products/{id}", productDto);
    }
    
    public async Task<bool> DeleteProductAsync(int id)
    {
        var result = await _httpClient.Fetch_DeleteAsync<DeleteResultDto>($"products/{id}");
        return result.Success;
    }
}

Dependencias

  • System.Net.Http.Json
  • System.Text.Json

Requisitos

  • .NET 6.0 o superior

Licencia

Este proyecto está licenciado bajo la Licencia MIT.

Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.2.0 145 3/22/2025
1.0.1 123 3/21/2025