VoluntasProgressus.APICore 2.1.4

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

VoluntasProgressus.APICore

Многоязычная документация для пакета API Core – централизованная обработка исключений и стандартизированные API-ответы. Includes full documentation in Russian, English, Deutsch, and 中文.


Русский / Russian

Описание

Этот пакет предоставляет механизм централизованной обработки исключений и формирования стандартизированных API-ответов:

  • Ошибки возвращаются в формате RFC 7807 Problem Details (application/problem+json)
  • Успешные ответы оборачиваются в унифицированный контейнер ApiResponse<T>
  • Подключение глобального фильтра GlobalResponseTransformer гарантирует автоматическую упаковку всех успешных ответов
  • Контроллер HealthController автоматически регистрируется при вызове services.AddApiCore() и доступен по маршруту /health для проверки состояния сервиса

Особенности

  • Централизованное перехватывание исключений через middleware
  • Цепочка IExceptionMapper для сопоставления исключений с ErrorResponse
  • Расширяемый builder ExceptionMapperBuilder
  • Автоматическая упаковка успешных ответов в ApiResponse<T>
  • Гарантированная унификация всех ответов через GlobalResponseTransformer
  • Поддержка HTTP-статусов и бизнес-ошибок
  • Логирование необработанных исключений
  • Автоматическая регистрация HealthController для мониторинга

Установка

dotnet add package VoluntasProgressus.APICore --version 2.1.4

Регистрация в DI

services.AddExceptionMappers(builder =>
{
    builder.Add<CustomExceptionMapper>();
});

// Регистрируем весь функционал API Core
services.AddApiCore();

// Включаем middleware централизованной обработки ошибок
app.UseErrorHandling();

// Контроллер HealthController теперь автоматически доступен
// по маршруту /health

Пример кастомного маппера

public class CustomExceptionMapper : IExceptionMapper
{
    public bool TryMap(Exception ex, HttpContext context, out ErrorResponse response)
    {
        if (ex is MyCustomException myEx)
        {
            response = new ErrorResponse
            {
                Type = "https://myapi/errors/custom",
                Title = "Моя пользовательская ошибка",
                Status = StatusCodes.Status422UnprocessableEntity,
                Instance = context.Request.Path,
                ErrorCode = "MyCustomError",
                RequestId = context.TraceIdentifier,
                AdditionalData = new Dictionary<string, object>
                {
                    ["Detail"] = myEx.Detail
                }
            };
            return true;
        }

        response = null!;
        return false;
    }
}

English

Description

Provides centralized exception handling and standardized API responses:

  • Errors are returned in RFC 7807 Problem Details format (application/problem+json)
  • Successful responses are wrapped in ApiResponse<T>
  • Optional GlobalResponseTransformer ensures all controller responses are automatically wrapped
  • The HealthController is automatically registered via services.AddApiCore() and accessible at /health for service health checks

Features

  • Centralized exception interception via middleware
  • Chain of IExceptionMapper to map exceptions to ErrorResponse
  • Extensible ExceptionMapperBuilder
  • Automatic wrapping of successful responses in ApiResponse<T>
  • Guaranteed unified response format via GlobalResponseTransformer
  • Supports HTTP statuses and business exceptions
  • Logging of unhandled exceptions
  • Auto-registration of HealthController for health monitoring

Installation

dotnet add package VoluntasProgressus.APICore --version 2.1.4

DI Registration

services.AddExceptionMappers(builder =>
{
    builder.Add<CustomExceptionMapper>();
});

// Registers all API Core functionality
services.AddApiCore();

// Enables centralized error handling middleware
app.UseErrorHandling();

// HealthController is now automatically available at /health

Custom Exception Mapper Example

public class CustomExceptionMapper : IExceptionMapper
{
    public bool TryMap(Exception ex, HttpContext context, out ErrorResponse response)
    {
        if (ex is MyCustomException myEx)
        {
            response = new ErrorResponse
            {
                Type = "https://myapi/errors/custom",
                Title = "My Custom Error",
                Status = StatusCodes.Status422UnprocessableEntity,
                Instance = context.Request.Path,
                ErrorCode = "MyCustomError",
                RequestId = context.TraceIdentifier,
                AdditionalData = new Dictionary<string, object>
                {
                    ["Detail"] = myEx.Detail
                }
            };
            return true;
        }

        response = null!;
        return false;
    }
}

Deutsch / German

Beschreibung

Dieses Paket bietet zentrale Ausnahmebehandlung und standardisierte API-Antworten:

  • Fehler werden im RFC 7807 Problem Details Format zurückgegeben (application/problem+json)
  • Erfolgreiche Antworten werden in ApiResponse<T> verpackt
  • GlobalResponseTransformer stellt sicher, dass alle Controller-Antworten automatisch verpackt werden
  • Der HealthController wird automatisch über services.AddApiCore() registriert und ist unter /health verfügbar

Funktionen

  • Zentrale Ausnahmeerfassung über Middleware
  • IExceptionMapper-Kette zur Zuordnung von Ausnahmen zu ErrorResponse
  • Erweiterbarer Builder ExceptionMapperBuilder
  • Automatisches Verpacken erfolgreicher Antworten in ApiResponse<T>
  • Einheitliches Antwortformat durch GlobalResponseTransformer
  • Unterstützung von HTTP-Statuscodes und Geschäftsausnahmen
  • Logging von nicht behandelten Ausnahmen
  • Automatische Registrierung von HealthController für Monitoring

Installation

dotnet add package VoluntasProgressus.APICore --version 2.1.4

DI-Registrierung

services.AddExceptionMappers(builder =>
{
    builder.Add<CustomExceptionMapper>();
});

// Registriert alle Funktionen von API Core
services.AddApiCore();

// Aktiviert zentrale Fehlerbehandlung Middleware
app.UseErrorHandling();

// HealthController ist nun automatisch unter /health verfügbar

Beispiel für benutzerdefinierten Exception Mapper

public class CustomExceptionMapper : IExceptionMapper
{
    public bool TryMap(Exception ex, HttpContext context, out ErrorResponse response)
    {
        if (ex is MyCustomException myEx)
        {
            response = new ErrorResponse
            {
                Type = "https://myapi/errors/custom",
                Title = "Mein benutzerdefinierter Fehler",
                Status = StatusCodes.Status422UnprocessableEntity,
                Instance = context.Request.Path,
                ErrorCode = "MyCustomError",
                RequestId = context.TraceIdentifier,
                AdditionalData = new Dictionary<string, object>
                {
                    ["Detail"] = myEx.Detail
                }
            };
            return true;
        }

        response = null!;
        return false;
    }
}

中文 / Chinese

描述

提供集中式异常处理和标准化 API 响应:

  • 错误以 RFC 7807 Problem Details 格式返回 (application/problem+json)
  • 成功响应封装在 ApiResponse<T>
  • 可选 GlobalResponseTransformer 确保所有控制器响应自动封装
  • HealthController 通过 services.AddApiCore() 自动注册,可通过 /health 检查服务状态

功能

  • 通过中间件集中拦截异常
  • IExceptionMapper 链将异常映射为 ErrorResponse
  • 可扩展的 ExceptionMapperBuilder
  • 自动将成功响应包装为 ApiResponse<T>
  • 通过 GlobalResponseTransformer 保证响应统一
  • 支持 HTTP 状态码和业务异常
  • 未处理异常日志记录
  • 自动注册 HealthController 以便监控服务

安装

dotnet add package VoluntasProgressus.APICore --version 2.1.4

DI 注册

services.AddExceptionMappers(builder =>
{
    builder.Add<CustomExceptionMapper>();
});

// 注册 API Core 所有功能
services.AddApiCore();

// 启用集中错误处理中间件
app.UseErrorHandling();

// HealthController 现已自动可用,访问路径 /health

自定义异常映射示例

public class CustomExceptionMapper : IExceptionMapper
{
    public bool TryMap(Exception ex, HttpContext context, out ErrorResponse response)
    {
        if (ex is MyCustomException myEx)
        {
            response = new ErrorResponse
            {
                Type = "https://myapi/errors/custom",
                Title = "我的自定义错误",
                Status = StatusCodes.Status422UnprocessableEntity,
                Instance = context.Request.Path,
                ErrorCode = "MyCustomError",
                RequestId = context.TraceIdentifier,
                AdditionalData = new Dictionary<string, object>
                {
                    ["Detail"] = myEx.Detail
                }
            };
            return true;
        }

        response = null!;
        return false;
    }
}

License / Лицензия / Lizenz / 许可

MIT License – см. LICENSE.txt

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.  net10.0 was computed.  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
2.1.9 74 9/12/2025
2.1.8 72 9/12/2025
2.1.7 73 9/12/2025
2.1.6 71 9/12/2025
2.1.5 73 9/12/2025
2.1.4 72 9/12/2025
2.1.3 77 9/12/2025

- Added HealthController with a simple /health endpoint for API monitoring.
- Updated AddApiResponseHandling to internal.
- Centralized exception handling and standardized API response handling improvements.