Pitasoft.Client 7.0.4

There is a newer version of this package available.
See the version list below for details.
dotnet add package Pitasoft.Client --version 7.0.4
                    
NuGet\Install-Package Pitasoft.Client -Version 7.0.4
                    
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="Pitasoft.Client" Version="7.0.4" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Pitasoft.Client" Version="7.0.4" />
                    
Directory.Packages.props
<PackageReference Include="Pitasoft.Client" />
                    
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 Pitasoft.Client --version 7.0.4
                    
#r "nuget: Pitasoft.Client, 7.0.4"
                    
#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.
#:package Pitasoft.Client@7.0.4
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Pitasoft.Client&version=7.0.4
                    
Install as a Cake Addin
#tool nuget:?package=Pitasoft.Client&version=7.0.4
                    
Install as a Cake Tool

Pitasoft.Client

NuGet Version NuGet Downloads License .NET Build Status

English | Castellano


English

Pitasoft.Client is a .NET library designed to simplify the consumption of RESTful services. It provides a robust base class and helpers to handle HTTP requests, JSON serialization, and common API patterns.

Features

  • Base REST Service: RestServiceBase provides methods for GET, POST, PUT, and DELETE operations, including batch processing support.
  • Modern HttpClient Management: Full support for IHttpClientFactory to ensure efficient connection management, socket pooling, and seamless integration with Dependency Injection.
  • Result Handling: Integrated with Pitasoft.Result and Pitasoft.Error for consistent and expressive response handling.
  • Query Helpers: Utilities to easily and safely manage query strings in URIs.
  • High Performance: Optimized for .NET 8, 9, and 10 using SearchValues, Span<char>, and efficient memory management.
  • Flexible Configuration: Multiple constructors to support custom HttpClient, IHttpClientFactory, Base URI, and JsonSerializerOptions.

Performance Optimizations (.NET 8/9/10)

The latest version includes significant performance improvements:

  • Zero-allocation URI parsing: Using ReadOnlySpan<char> and AsSpan() to avoid unnecessary string allocations during query string manipulation.
  • Fast Search: Implementation of SearchValues<char> for ultra-fast detection of control characters (?, #).
  • Memory Efficiency: StringBuilder pre-sizing and optimized JSON deserialization paths.
Method Mean Ratio Allocated
AddSingleQueryString 34.31 ns 1.00 456 B
AddMultipleQueryStrings 118.62 ns 1.00 960 B

Installation

Install via NuGet:

dotnet add package Pitasoft.Client

Basic Usage

1. Define your Service

Inherit from RestServiceBase to create your API client.

public class MyApiService : RestServiceBase
{
    // Recommended: Use IHttpClientFactory
    public MyApiService(IHttpClientFactory factory) 
        : base(factory, nameof(MyApiService)) { }

    // GET a single entity
    public async Task<ResultEntity<MyData>> GetDataAsync(int id)
    {
        return await GetAsync<MyData>($"api/data/{id}");
    }

    // GET multiple entities with query strings
    public async Task<ResultEntities<MyData>> GetAllDataAsync(string filter, int page = 1)
    {
        // Use QueryHelpers to build the URI safely and efficiently
        var queryParams = new Dictionary<string, string>
        {
            { "filter", filter },
            { "page", page.ToString() }
        };
        var uri = QueryHelpers.AddQueryString("api/data", queryParams);
        return await GetsAsync<MyData>(uri);
    }

    // POST an entity
    public async Task<ResultEntity<MyData>> CreateDataAsync(MyData data)
    {
        return await PostAsync("api/data", data);
    }
}
2. Register in Dependency Injection

In your Program.cs or Startup.cs:

builder.Services.AddHttpClient(nameof(MyApiService), client => 
{
    client.BaseAddress = new Uri("https://api.example.com/");
    client.DefaultRequestHeaders.Add("Accept", "application/json");
});

builder.Services.AddScoped<MyApiService>();
3. Advanced Configuration
// Custom JSON options
var options = new JsonSerializerOptions 
{ 
    PropertyNameCaseInsensitive = true,
    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};

// Initialize with options
var service = new MyApiService(httpClientFactory, "MyClient", options);

Castellano

Pitasoft.Client es una librería .NET diseñada para simplificar el consumo de servicios RESTful. Proporciona una clase base robusta y utilidades para manejar peticiones HTTP, serialización JSON y patrones comunes de API, siguiendo las mejores prácticas de .NET.

Características

  • Servicio REST Base: RestServiceBase proporciona métodos para operaciones GET, POST, PUT y DELETE, incluyendo soporte para procesamiento por lotes (batch).
  • Gestión Moderna de HttpClient: Soporte completo para IHttpClientFactory para asegurar una gestión eficiente de conexiones, pooling de sockets y una integración fluida con Inyección de Dependencias.
  • Manejo de Resultados: Integrado con Pitasoft.Result y Pitasoft.Error para un manejo de respuestas consistente y expresivo.
  • Helpers de Consulta: Utilidades para gestionar de forma fácil y segura cadenas de consulta (query strings) en URIs.
  • Alto Rendimiento: Optimizado para .NET 8, 9 y 10 utilizando SearchValues, Span<char> y gestión eficiente de memoria.
  • Configuración Flexible: Múltiples constructores para soportar HttpClient personalizado, IHttpClientFactory, URI base y JsonSerializerOptions.

Optimizaciones de Rendimiento (.NET 8/9/10)

La última versión incluye mejoras significativas de rendimiento:

  • Análisis de URIs sin asignaciones: Uso de ReadOnlySpan<char> y AsSpan() para evitar la creación de cadenas temporales innecesarias.
  • Búsqueda Rápida: Implementación de SearchValues<char> para la detección ultra-rápida de caracteres de control (?, #).
  • Eficiencia de Memoria: Pre-dimensionamiento de StringBuilder y rutas de deserialización JSON optimizadas.
Método Media Ratio Memoria
AddSingleQueryString 34.31 ns 1.00 456 B
AddMultipleQueryStrings 118.62 ns 1.00 960 B

Instalación

Instalar a través de NuGet:

dotnet add package Pitasoft.Client

Uso Básico

1. Define tu Servicio

Hereda de RestServiceBase para crear tu cliente de API.

public class MyApiService : RestServiceBase
{
    // Recomendado: Usar IHttpClientFactory
    public MyApiService(IHttpClientFactory factory) 
        : base(factory, nameof(MyApiService)) { }

    // Obtener una única entidad
    public async Task<ResultEntity<MyData>> GetDataAsync(int id)
    {
        return await GetAsync<MyData>($"api/data/{id}");
    }

    // Obtener múltiples entidades con parámetros de consulta
    public async Task<ResultEntities<MyData>> GetAllDataAsync(string filter, int pagina = 1)
    {
        // Usa QueryHelpers para construir la URI de forma segura y eficiente
        var queryParams = new Dictionary<string, string>
        {
            { "filter", filter },
            { "page", pagina.ToString() }
        };
        var uri = QueryHelpers.AddQueryString("api/data", queryParams);
        return await GetsAsync<MyData>(uri);
    }

    // Enviar (POST) una entidad
    public async Task<ResultEntity<MyData>> CreateDataAsync(MyData data)
    {
        return await PostAsync("api/data", data);
    }
}
2. Registro en Inyección de Dependencias

En tu Program.cs o Startup.cs:

builder.Services.AddHttpClient(nameof(MyApiService), client => 
{
    client.BaseAddress = new Uri("https://api.example.com/");
    client.DefaultRequestHeaders.Add("Accept", "application/json");
});

builder.Services.AddScoped<MyApiService>();
3. Configuración Avanzada
// Opciones JSON personalizadas
var options = new JsonSerializerOptions 
{ 
    PropertyNameCaseInsensitive = true,
    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};

// Inicializar con opciones
var service = new MyApiService(httpClientFactory, "MyClient", options);

Autor

Sebastián Martínez Pérez

License

Copyright © 2021-2026 Pitasoft, S.L. Licensed under the LICENSE.txt provided in this repository.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  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.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.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
8.1.2 134 4/17/2026
8.1.1 147 3/26/2026
8.0.1 134 3/24/2026
7.0.7 137 3/20/2026
7.0.6 138 3/13/2026
7.0.5 144 3/2/2026
7.0.4 137 2/25/2026
7.0.3 145 2/12/2026
7.0.2 155 1/26/2026
7.0.1 160 1/26/2026
6.5.5 359 5/27/2025
6.5.4 338 5/27/2025
6.5.3 328 5/25/2025
6.5.2 342 5/25/2025
6.5.1 290 5/23/2025
6.5.0 341 5/19/2025
6.0.0 372 8/21/2024
5.2.2 377 5/17/2024
5.2.1 342 5/17/2024
5.2.0 455 11/20/2023
Loading failed