VoluntasProgressus.APICore
2.2.2
See the version list below for details.
dotnet add package VoluntasProgressus.APICore --version 2.2.2
NuGet\Install-Package VoluntasProgressus.APICore -Version 2.2.2
<PackageReference Include="VoluntasProgressus.APICore" Version="2.2.2" />
<PackageVersion Include="VoluntasProgressus.APICore" Version="2.2.2" />
<PackageReference Include="VoluntasProgressus.APICore" />
paket add VoluntasProgressus.APICore --version 2.2.2
#r "nuget: VoluntasProgressus.APICore, 2.2.2"
#:package VoluntasProgressus.APICore@2.2.2
#addin nuget:?package=VoluntasProgressus.APICore&version=2.2.2
#tool nuget:?package=VoluntasProgressus.APICore&version=2.2.2
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]или конфигурацию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 2.2.2
Настройка через 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]
[ApiController]
[Route("example")]
public class ExampleController : ControllerBase
{
[HttpGet("ignored")]
public IActionResult GetIgnored()
{
return Ok(new { message = "Этот ответ не будет обёрнут" });
}
}
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
[SkipResponseWrapping]orResponseHandlingSettings: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
Configuration via appsettings.json
{
"ResponseHandling": {
"ExcludedPaths": [ "/swagger", "/docs" ]
}
}
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 for controller/method
[SkipResponseWrapping]
[ApiController]
[Route("example")]
public class ExampleController : ControllerBase
{
[HttpGet("ignored")]
public IActionResult GetIgnored()
{
return Ok(new { message = "This response will not be wrapped" });
}
}
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
[SkipResponseWrapping]oderResponseHandlingSettings:ExcludedPathsausgeschlossen werden - Middleware für Response Handling wurde umbenannt (
UseErrorHandling→UseResponseHandling) - Zyklische Abhängigkeiten bei der Registrierung von IExceptionMapper wurden behoben
Funktionen
- Zentrale Ausnahmeerfassung über Middleware
IExceptionMapper-Kette zur Zuordnung von Ausnahmen zuErrorResponse- Erweiterbarer Builder
ExceptionMapperBuilder - Automatisches Verpacken erfolgreicher Antworten in
ApiResponse<T> - Unterstützung von HTTP-Statuscodes und Geschäftslogikfehlern
- Logging von nicht behandelten Ausnahmen
- Ausschluss bestimmter Endpunkte über Attribut oder Konfiguration
- Automatische Registrierung von
HealthControllerfür Monitoring
中文 / Chinese
描述
提供集中式异常处理和标准化 API 响应:
- 错误以 RFC 7807 Problem Details 格式返回 (
application/problem+json) - 成功响应封装在
ApiResponse<T>中 HealthController通过services.AddApiCore()自动注册,可通过/health检查服务状态- 支持 Autofac DI 容器
- 可以通过
[SkipResponseWrapping]或ResponseHandlingSettings:ExcludedPaths配置排除特定路由或方法 - 修复注册 IExceptionMapper 时的循环依赖
- 中间件已重命名:
UseErrorHandling→UseResponseHandling
功能
- 通过中间件集中拦截异常
IExceptionMapper链将异常映射为ErrorResponse- 可扩展的
ExceptionMapperBuilder - 自动将成功响应包装为
ApiResponse<T> - 支持 HTTP 状态码和业务异常
- 未处理异常日志记录
- 通过特性或配置排除特定端点
- 自动注册
HealthController以便监控服务
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.
- Migrated from .NET 9.0 to .NET 8.0 for better compatibility.
- Added support for Autofac as a DI container.
- Fixed issue with circular dependencies when registering IExceptionMapper.
- Updated documentation for using API Core.
- Updated dependencies and libraries to the latest versions.
- Renamed extension methods for clarity (`UseErrorHandling` → `UseResponseHandling`).