将 HealthCheck 端点集成到 dotnet core 上的 swagger(开放 API)UI 中

2023-12-19

我正在使用 Dotnet Core 健康检查,如上所述here https://blogs.msdn.microsoft.com/webdev/2018/08/22/asp-net-core-2-2-0-preview1-healthcheck/?WT.mc_id=-blog-scottha。简而言之,它看起来像这样:

首先,您像这样配置服务:

services.AddHealthChecks()
    .AddSqlServer("connectionString", name: "SQlServerHealthCheck")
    ... // Add multiple other checks

然后,您注册一个端点,如下所示:

app.UseHealthChecks("/my/healthCheck/endpoint");

我们还使用 Swagger(又名开放 API),并且通过 Swagger UI 查看所有端点,但看不到运行状况检查端点。

有没有办法将其添加到控制器方法中,以便 Swagger 自动获取端点,或者以其他方式将其与 swagger 集成?

到目前为止,我发现的最佳解决方案是添加自定义硬编码端点(就像这里描述的那样 https://stackoverflow.com/questions/48668107/add-endpoints-manually-with-swashbuckle-swagger),但是维护起来不太好。


我使用了这种方法,它对我来说效果很好:https://www.codit.eu/blog/documenting-asp-net-core-health-checks-with-openapi 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 中正确显示。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 HealthCheck 端点集成到 dotnet core 上的 swagger(开放 API)UI 中 的相关文章

随机推荐