Pitasoft.Result 7.0.2

There is a newer version of this package available.
See the version list below for details.
dotnet add package Pitasoft.Result --version 7.0.2
                    
NuGet\Install-Package Pitasoft.Result -Version 7.0.2
                    
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.Result" Version="7.0.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Pitasoft.Result" Version="7.0.2" />
                    
Directory.Packages.props
<PackageReference Include="Pitasoft.Result" />
                    
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.Result --version 7.0.2
                    
#r "nuget: Pitasoft.Result, 7.0.2"
                    
#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.Result@7.0.2
                    
#: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.Result&version=7.0.2
                    
Install as a Cake Addin
#tool nuget:?package=Pitasoft.Result&version=7.0.2
                    
Install as a Cake Tool

Pitasoft.Result

NuGet

English | Castellano


English

Pitasoft.Result is a .NET library designed to standardize responses from REST services and internal application layers. It provides a robust set of classes to wrap data, status codes, and error collections, facilitating a unified communication contract between APIs, services, and clients.

Features

  • Standardized Responses: Unify your API outputs using Result, ResultEntity<T>, and ResultEntities<T>.
  • Fluent Error Handling: Easily add validation errors, exceptions, or business rule violations using a fluent interface.
  • Rich Status Management: Built-in StatusResult enum covering common API scenarios (Success, Not Found, Validation Errors, Database Errors, etc.).
  • Batch Operations: Specialized support for processing multiple items with ResultBatch<T>.
  • Pagination Support: ResultEntities<T> includes metadata like total count, and the library provides PagingParameters for request handling.
  • Extensions: Useful helper methods to check for success, specific errors, or state.

Installation

dotnet add package Pitasoft.Result

Core Components

1. Simple Result (Result)

Used for operations that don't return data, only a completion status and optional errors.

public Result DeleteUser(int id)
{
    if (id <= 0) 
        return Result.ValidationError().AddError("id", "Invalid ID");
    
    var deleted = _repository.Delete(id);
    if (!deleted) return Result.NotExists();
    
    return Result.Deleted();
}
2. Result with Entity (ResultEntity<T>)

Used for operations returning a single object.

public ResultEntity<User> GetUser(int id)
{
    var user = _repository.Find(id);
    if (user == null) return ResultEntity<User>.NotExists();
    
    return ResultEntity<User>.Ok(user);
}
3. Result with Multiple Entities (ResultEntities<T>)

Used for lists or paged results. It includes an optional Count property for total records.

public ResultEntities<User> GetUsers(EntityParameters params)
{
    var (users, total) = _repository.GetAll(params);
    return ResultEntities<User>.Ok(users, total);
}
4. Batch Result (ResultBatch<T>)

Used for processing multiple items in a single request, providing a global status and individual results for each item.

public ResultBatch<User> ImportUsers(List<User> users)
{
    var results = users.Select(u => Process(u)).ToList();
    return ResultBatch<User>.Ok(results);
}

Error Handling

The library supports a fluent API for adding errors, which are stored in an ErrorCollection:

return Result.ValidationError()
    .AddError("Email", "Invalid format")
    .AddError("Password", "Too short")
    .AddError(new Exception("Inner system error"));

Status Codes (StatusResult)

Status Category Description
Ok, Added, Updated, Deleted Success Successful operations.
NoExist Informational Requested resource was not found.
Warning Informational Completed with non-critical issues.
ValidationError Error Client-side input validation failed.
DataError, DatabaseError Error Issues with data processing or persistence.
ConcurrencyError Error Data was modified by another process.
Unauthorized Security Authentication or authorization failed.
Exception Error An unhandled exception occurred.

Extensions

Import Pitasoft.Result.Extensions to use these helper methods on any IResult:

  • result.IsSuccess(): Returns true if status is Ok, Added, Updated, or Deleted.
  • result.IsError(): Returns true for most error-related statuses.
  • result.IsNotExist(): Returns true if the resource was not found.
  • result.HasErrors(): Returns true if there are any errors in the Errors collection.
  • result.IsSuccessOrNotExist(): Useful for "Delete" operations where both cases are often handled similarly.

Castellano

Pitasoft.Result es una librería .NET diseñada para estandarizar las respuestas de los servicios REST y las capas internas de la aplicación. Proporciona un conjunto robusto de clases para envolver datos, códigos de estado y colecciones de errores, facilitando un contrato de comunicación unificado entre APIs, servicios y clientes.

Características

  • Respuestas Estandarizadas: Unifica las salidas de tu API usando Result, ResultEntity<T> y ResultEntities<T>.
  • Gestión de Errores Fluida: Añade fácilmente errores de validación, excepciones o violaciones de reglas de negocio mediante una interfaz fluida.
  • Gestión de Estados Enriquecida: Enumerado StatusResult integrado que cubre escenarios comunes (Éxito, No Encontrado, Errores de Validación, Errores de Base de Datos, etc.).
  • Operaciones por Lote: Soporte especializado para procesar múltiples elementos con ResultBatch<T>.
  • Soporte para Paginación: ResultEntities<T> incluye metadatos como el conteo total, y la librería proporciona PagingParameters para el manejo de peticiones.
  • Extensiones: Métodos de ayuda útiles para comprobar éxito, errores específicos o estado.

Instalación

dotnet add package Pitasoft.Result

Componentes Principales

1. Resultado Simple (Result)

Utilizado para operaciones que no devuelven datos, solo un estado de finalización y errores opcionales.

public Result DeleteUser(int id)
{
    if (id <= 0) 
        return Result.ValidationError().AddError("id", "ID no válido");
    
    var deleted = _repository.Delete(id);
    if (!deleted) return Result.NotExists();
    
    return Result.Deleted();
}
2. Resultado con Entidad (ResultEntity<T>)

Utilizado para operaciones que devuelven un único objeto.

public ResultEntity<User> GetUser(int id)
{
    var user = _repository.Find(id);
    if (user == null) return ResultEntity<User>.NotExists();
    
    return ResultEntity<User>.Ok(user);
}
3. Resultado con Múltiples Entidades (ResultEntities<T>)

Utilizado para listas o resultados paginados. Incluye una propiedad opcional Count para el total de registros.

public ResultEntities<User> GetUsers(EntityParameters params)
{
    var (users, total) = _repository.GetAll(params);
    return ResultEntities<User>.Ok(users, total);
}
4. Resultado por Lote (ResultBatch<T>)

Utilizado para procesar múltiples elementos en una sola petición, proporcionando un estado global y resultados individuales para cada elemento.

public ResultBatch<User> ImportUsers(List<User> users)
{
    var results = users.Select(u => Process(u)).ToList();
    return ResultBatch<User>.Ok(results);
}

Gestión de Errores

La librería soporta una API fluida para añadir errores, que se almacenan en una ErrorCollection:

return Result.ValidationError()
    .AddError("Email", "Formato no válido")
    .AddError("Password", "Demasiado corta")
    .AddError(new Exception("Error interno del sistema"));

Códigos de Estado (StatusResult)

Estado Categoría Descripción
Ok, Added, Updated, Deleted Éxito Operaciones exitosas.
NoExist Informativo El recurso solicitado no fue encontrado.
Warning Informativo Completado con problemas no críticos.
ValidationError Error Falló la validación de entrada del cliente.
DataError, DatabaseError Error Problemas en el procesamiento o persistencia de datos.
ConcurrencyError Error Los datos fueron modificados por otro proceso.
Unauthorized Seguridad Falló la autenticación o autorización.
Exception Error Ocurrió una excepción no controlada.

Extensiones

Importa Pitasoft.Result.Extensions para usar estos métodos de ayuda en cualquier IResult:

  • result.IsSuccess(): Devuelve true si el estado es Ok, Added, Updated o Deleted.
  • result.IsError(): Devuelve true para la mayoría de los estados relacionados con errores.
  • result.IsNotExist(): Devuelve true si el recurso no fue encontrado.
  • result.HasErrors(): Devuelve true si hay algún error en la colección Errors.
  • result.IsSuccessOrNotExist(): Útil para operaciones "Delete" donde ambos casos suelen manejarse de forma similar.

License

Copyright © 2019-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 (9)

Showing the top 5 NuGet packages that depend on Pitasoft.Result:

Package Downloads
Pitasoft.Client

.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.

Pitasoft.Web

Librerias basicas de aplicaciones web

Pitasoft.Blazor.Result

Application of the functionalities of the Pitasoft.Blazor package, adding functionalities of Pitasoft.Result.

Pitasoft.Mail

E-Mail server service.

Pitasoft.Result.AspNetCore

ASP.NET Core integration for Pitasoft.Result. Provides HTTP result mapping, JSON helpers, DI-based configuration, and exception handling for MVC and Minimal APIs.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
7.4.1 157 4/19/2026
7.3.2 218 4/3/2026
7.3.1 357 3/26/2026
7.2.9 160 3/24/2026
7.2.8 138 3/23/2026
7.2.7 140 3/22/2026
7.2.6 170 3/20/2026
7.2.5 142 3/20/2026
7.2.4 206 3/13/2026
7.2.3 143 3/11/2026
7.2.2 164 3/10/2026
7.2.1 155 3/9/2026
7.1.4 194 3/2/2026
7.1.3 181 2/24/2026
7.1.2 148 2/24/2026
7.1.1 189 2/23/2026
7.0.2 174 2/12/2026
7.0.1 201 1/26/2026
6.5.7 391 5/27/2025
6.5.6 359 5/27/2025
Loading failed