/
afanasevn
/
PdfEncoder
Обзор
Документация
Войти
/
afanasevn
/
PdfEncoder
Код
Запросы
0
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
src/PdfEncoder.Api/Controllers/HealthController.cs
108 строк
4 KB
IBS\NAfanasev
Add project files.
01 июл 2026, 14:54
01 июл 2026, 14:54
8414644
Код
Авторство
О чём код?
using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Diagnostics.HealthChecks; using PdfEncoder.Application.Health; namespace PdfEncoder.Api.Controllers; /// <summary> /// Проверка работоспособности сервиса. /// </summary> [ApiController] [Route("")] public sealed class HealthController(HealthCheckService healthCheckService) : ControllerBase { /// <summary> /// Возвращает агрегированный статус health checks. /// </summary> [HttpGet("health")] [ProducesResponseType(typeof(HealthResponse), StatusCodes.Status200OK)] [ProducesResponseType(typeof(HealthResponse), StatusCodes.Status503ServiceUnavailable)] public async Task<IActionResult> Get(CancellationToken ct) { var report = await healthCheckService.CheckHealthAsync(ct); var checks = report.Entries.ToDictionary( entry => entry.Key, entry => MapCheckStatus(entry.Value)); var response = new HealthResponse { Status = report.Status == HealthStatus.Healthy ? "healthy" : "unhealthy", Checks = checks }; return report.Status == HealthStatus.Healthy ? Ok(response) : StatusCode(StatusCodes.Status503ServiceUnavailable, response); } private static string MapCheckStatus(HealthReportEntry entry) { if (entry.Description?.Contains("skipped", StringComparison.OrdinalIgnoreCase) == true) { return "skipped"; } return entry.Status switch { HealthStatus.Healthy => "ok", HealthStatus.Degraded when entry.Description?.Contains("skipped", StringComparison.OrdinalIgnoreCase) == true => "skipped", HealthStatus.Degraded => "degraded", _ => "error" }; } } /// <summary> /// Глобальная обработка исключений в формате RFC 7807 Problem Details. /// </summary> public static class ProblemDetailsConfiguration { /// <summary> /// Настраивает Problem Details для API. /// </summary> public static IServiceCollection AddPdfEncoderProblemDetails(this IServiceCollection services) { services.AddProblemDetails(options => { options.CustomizeProblemDetails = context => { context.ProblemDetails.Extensions["traceId"] = context.HttpContext.TraceIdentifier; }; }); return services; } /// <summary> /// Подключает middleware обработки исключений. /// </summary> public static WebApplication UsePdfEncoderExceptionHandling(this WebApplication app) { app.UseExceptionHandler(errorApp => { errorApp.Run(async context => { var exceptionFeature = context.Features.Get<IExceptionHandlerFeature>(); var problemDetails = new ProblemDetails { Type = "https://pdfencoder.local/errors/internal", Title = "Internal server error", Status = StatusCodes.Status500InternalServerError, Detail = app.Environment.IsDevelopment() ? exceptionFeature?.Error.Message : "An unexpected error occurred.", Instance = context.Request.Path }; problemDetails.Extensions["traceId"] = context.TraceIdentifier; context.Response.StatusCode = StatusCodes.Status500InternalServerError; context.Response.ContentType = "application/problem+json"; await context.Response.WriteAsJsonAsync(problemDetails); }); }); return app; } }