VoluntasProgressus.APICore
3.0.0
dotnet add package VoluntasProgressus.APICore --version 3.0.0
NuGet\Install-Package VoluntasProgressus.APICore -Version 3.0.0
<PackageReference Include="VoluntasProgressus.APICore" Version="3.0.0" />
<PackageVersion Include="VoluntasProgressus.APICore" Version="3.0.0" />
<PackageReference Include="VoluntasProgressus.APICore" />
paket add VoluntasProgressus.APICore --version 3.0.0
#r "nuget: VoluntasProgressus.APICore, 3.0.0"
#:package VoluntasProgressus.APICore@3.0.0
#addin nuget:?package=VoluntasProgressus.APICore&version=3.0.0
#tool nuget:?package=VoluntasProgressus.APICore&version=3.0.0
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 для обработки ответов:
UseErrorHandling→UseResponseHandling
Установка
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> HealthControlleris automatically registered viaservices.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 viaResponseHandlingSettings:ExcludedPathsin configuration - Circular dependencies when registering
IExceptionMapperare fixed - Middleware renamed for clarity:
UseErrorHandling→UseResponseHandling
Features
- Centralized exception interception via middleware
- Chain of
IExceptionMapperto map exceptions toErrorResponse - 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
HealthControllerfor 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 HealthControllerwird automatisch viaservices.AddApiCore()unter/healthregistriert- 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 überExcludedPathsausgeschlossen werden - Middleware für Response Handling wurde umbenannt (
UseErrorHandling→UseResponseHandling) - 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 时的循环依赖
- 中间件已重命名:
UseErrorHandling→UseResponseHandling
License / Лицензия / Lizenz / 许可
MIT License – см. LICENSE.txt
| Product | Versions 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. |
-
net8.0
- Autofac (>= 8.4.0)
- Autofac.Extensions.DependencyInjection (>= 10.0.0)
- Microsoft.Extensions.Configuration.Abstractions (>= 10.0.0-rc.2.25502.107)
- Microsoft.Extensions.Http (>= 10.0.0-rc.2.25502.107)
- Microsoft.Extensions.Logging.Abstractions (>= 10.0.0-rc.2.25502.107)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
- 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).