swagger - 将 HealthCheck 端点集成到 dotnet core 上的 swagger (open API) UI
问题描述
我正在使用此处描述的 Dotnet Core 健康检查。简而言之,它看起来像这样:
首先,您像这样配置服务:
services.AddHealthChecks()
.AddSqlServer("connectionString", name: "SQlServerHealthCheck")
... // Add multiple other checks
然后,您像这样注册一个端点:
app.UseHealthChecks("/my/healthCheck/endpoint");
我们也在使用 Swagger(又名 Open API),我们通过 Swagger UI 查看所有端点,但看不到健康检查端点。
有没有办法将此添加到控制器方法中,以便 Swagger 自动拾取端点,或者以另一种方式将其与 swagger 集成?
到目前为止,我发现的最佳解决方案是添加一个自定义硬编码端点(如此处所述),但维护起来并不好。
解决方案
我使用了这种方法,对我来说效果很好:https ://www.codit.eu/blog/documenting-asp-net-core-health-checks-with-openapi
添加一个新的控制器,例如 HealthController 并将 HealthCheckService 注入到构造函数中。当您在 Startup.cs 中调用 AddHealthChecks 时,HealthCheckService 将作为依赖项添加:
重建时,HealthController 应该出现在 Swagger 中:
[Route("api/v1/health")]
public class HealthController : Controller
{
private readonly HealthCheckService _healthCheckService;
public HealthController(HealthCheckService healthCheckService)
{
_healthCheckService = healthCheckService;
}
/// <summary>
/// Get Health
/// </summary>
/// <remarks>Provides an indication about the health of the API</remarks>
/// <response code="200">API is healthy</response>
/// <response code="503">API is unhealthy or in degraded state</response>
[HttpGet]
[ProducesResponseType(typeof(HealthReport), (int)HttpStatusCode.OK)]
[SwaggerOperation(OperationId = "Health_Get")]
public async Task<IActionResult> Get()
{
var report = await _healthCheckService.CheckHealthAsync();
return report.Status == HealthStatus.Healthy ? Ok(report) : StatusCode((int)HttpStatusCode.ServiceUnavailable, report);
}
}
我注意到的一件事是端点仍然是“/health”(或者您在 Startup.cs 中设置的任何内容)而不是“/api/vxx/health”,但它仍然会在 Swagger 中正确显示。