VoluntasProgressus.APICore 3.0.0

dotnet add package VoluntasProgressus.APICore --version 3.0.0
                    
NuGet\Install-Package VoluntasProgressus.APICore -Version 3.0.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="VoluntasProgressus.APICore" Version="3.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="VoluntasProgressus.APICore" Version="3.0.0" />
                    
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 3.0.0
                    
#r "nuget: VoluntasProgressus.APICore, 3.0.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.
#:package VoluntasProgressus.APICore@3.0.0
                    
#: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=3.0.0
                    
Install as a Cake Addin
#tool nuget:?package=VoluntasProgressus.APICore&version=3.0.0
                    
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>
  • Контроллер HealthController автоматически регистрируется при вызове services.AddApiCore() и доступен по маршруту /health для проверки состояния сервиса
  • Поддерживается DI-контейнер Autofac
  • Можно исключать определённые маршруты или методы из обработки через расширенный атрибут [SkipResponseWrapping] с указанием конкретных кодов или диапазонов HTTP-статусов, например "2xx", "3xx", 201, 303 и т.п., а также через конфигурацию ResponseHandlingSettings:ExcludedPaths в appsettings.json

Особенности

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

Установка

dotnet add package VoluntasProgressus.APICore --version 3.0.0

Настройка через appsettings.json

{
  "ResponseHandling": {
    "ExcludedPaths": [ "/swagger", "/docs" ]
  }
}

Регистрация в DI (.NET DI или Autofac)

Через стандартный Microsoft DI:

services.AddApiCore(Configuration);

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

app.UseResponseHandling();

Через Autofac:

var builder = new ContainerBuilder();
builder.AddApiCore(Configuration);

// Регистрируем свои ExceptionMapper через Autofac
builder.RegisterType<CustomExceptionMapper>()
       .As<IExceptionMapper>()
       .SingleInstance();

var container = builder.Build();

Пример использования расширенного атрибута [SkipResponseWrapping]

  • Пропустить все успешные ответы 2xx и код 400: [SkipResponseWrapping("2xx", 400)]
  • Пропустить только ответы с кодами 201 и 303: [SkipResponseWrapping(201, 303)]
  • Можно комбинировать на уровне контроллера и отдельных методов.

Пример:

[SkipResponseWrapping("2xx", 400)]
[ApiController]
[Route("example")]
public class ExampleController : ControllerBase
{
    [HttpGet("ignored")]
    public IActionResult GetIgnored()
    {
        return Ok(new { message = "Этот ответ не будет обёрнут" });
    }

    [SkipResponseWrapping(201, 303)]
    [HttpGet("partial")]
    public IActionResult GetPartial()
    {
        return StatusCode(201, new { message = "Только определённые коды не будут обёрнуты" });
    }
}

HTTP-статусы 1xx (информационные) middleware обычно не обрабатывает, так как они не содержат тела и не нуждаются в оборачивании.


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>
  • HealthController is automatically registered via services.AddApiCore() at /health
  • Supports Autofac as a DI container
  • Routes or methods can be excluded from wrapping via the extended [SkipResponseWrapping] attribute with HTTP codes or ranges ("2xx", "3xx", 201, 303, etc.) or via ResponseHandlingSettings:ExcludedPaths in configuration
  • Circular dependencies when registering IExceptionMapper are fixed
  • Middleware renamed for clarity: UseErrorHandlingUseResponseHandling

Features

  • Centralized exception interception via middleware
  • Chain of IExceptionMapper to map exceptions to ErrorResponse
  • Extensible ExceptionMapperBuilder
  • Automatic wrapping of successful responses in ApiResponse<T>
  • Supports HTTP statuses and business exceptions
  • Logging of unhandled exceptions
  • Exclude specific endpoints from wrapping via attribute or configuration
  • Auto-registration of HealthController for health monitoring

DI Registration

Standard Microsoft DI:

services.AddApiCore(Configuration);

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

app.UseResponseHandling();

Autofac:

var builder = new ContainerBuilder();
builder.AddApiCore(Configuration);

builder.RegisterType<CustomExceptionMapper>()
       .As<IExceptionMapper>()
       .SingleInstance();

var container = builder.Build();

Skip wrapping using extended attribute

  • Skip all 2xx responses and 400: [SkipResponseWrapping("2xx", 400)]
  • Skip only 201 and 303 responses: [SkipResponseWrapping(201, 303)]

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
  • HealthController wird automatisch via services.AddApiCore() unter /health registriert
  • Unterstützt Autofac als DI-Container
  • Bestimmte Routen oder Methoden können über den erweiterten [SkipResponseWrapping]-Attribut mit HTTP-Codes oder Bereichen ("2xx", "3xx", 201, 303 etc.) oder über ExcludedPaths ausgeschlossen werden
  • Middleware für Response Handling wurde umbenannt (UseErrorHandlingUseResponseHandling)
  • Zyklische Abhängigkeiten bei der Registrierung von IExceptionMapper wurden behoben

中文 / Chinese

描述

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

  • 错误以 RFC 7807 Problem Details 格式返回 (application/problem+json)
  • 成功响应封装在 ApiResponse<T>
  • HealthController 通过 services.AddApiCore() 自动注册,可通过 /health 检查服务状态
  • 支持 Autofac DI 容器
  • 可以通过扩展的 [SkipResponseWrapping] 特性按 HTTP 状态码或范围排除特定路由或方法(如 "2xx""3xx"、具体码 201、303 等),也可以通过配置 ResponseHandlingSettings:ExcludedPaths 排除
  • 修复注册 IExceptionMapper 时的循环依赖
  • 中间件已重命名:UseErrorHandlingUseResponseHandling

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

MIT License – см. LICENSE.txt

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 was computed.  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
3.0.0 155 10/25/2025
2.2.2 103 10/25/2025
2.1.9 243 9/12/2025
2.1.8 177 9/12/2025
2.1.7 178 9/12/2025
2.1.6 164 9/12/2025
2.1.5 177 9/12/2025
2.1.4 166 9/12/2025
2.1.3 166 9/12/2025

- Added extended SkipResponseWrappingAttribute to allow flexible exclusion of response wrapping based on HTTP status codes (e.g., "2xx", "3xx", or specific codes like 201, 303).