VoluntasProgressus.APICore
2.1.4
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
<PackageReference Include="VoluntasProgressus.APICore" Version="2.1.4" />
<PackageVersion Include="VoluntasProgressus.APICore" Version="2.1.4" />
<PackageReference Include="VoluntasProgressus.APICore" />
paket add VoluntasProgressus.APICore --version 2.1.4
#r "nuget: VoluntasProgressus.APICore, 2.1.4"
#:package VoluntasProgressus.APICore@2.1.4
#addin nuget:?package=VoluntasProgressus.APICore&version=2.1.4
#tool nuget:?package=VoluntasProgressus.APICore&version=2.1.4
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 viaservices.AddApiCore()
and accessible at/health
for service health checks
Features
- Centralized exception interception via middleware
- Chain of
IExceptionMapper
to map exceptions toErrorResponse
- 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 überservices.AddApiCore()
registriert und ist unter/health
verfügbar
Funktionen
- Zentrale Ausnahmeerfassung über Middleware
IExceptionMapper
-Kette zur Zuordnung von Ausnahmen zuErrorResponse
- 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 | Versions 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. |
-
net9.0
- Microsoft.Extensions.Configuration.Abstractions (>= 9.0.9)
- Microsoft.Extensions.Http (>= 9.0.9)
- Microsoft.Extensions.Logging.Abstractions (>= 9.0.9)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
- Added HealthController with a simple /health endpoint for API monitoring.
- Updated AddApiResponseHandling to internal.
- Centralized exception handling and standardized API response handling improvements.