Skip to content

Instantly share code, notes, and snippets.

@saminaazad
Last active October 11, 2019 03:23
public class ApiHealthCheck : IHealthCheck
{
private readonly HttpContext _httpContext;
public ApiHealthCheck(IHttpContextAccessor contextAccessor)
{
_httpContext = contextAccessor?.HttpContext;
}
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
try
{
using (var httpClient = new HttpClient())
{
var url = new Uri($"{_httpContext.Request.Scheme}://{_httpContext.Request.Host}/ping");
var response = await httpClient.GetAsync(url);
if (!response.IsSuccessStatusCode)
{
return HealthCheckResult.Unhealthy($"Didn't receive OK response from /ping endpoint. Response Phrase: {response.ReasonPhrase}.");
}
}
}
catch (Exception ex)
{
return HealthCheckResult.Unhealthy($"Error ocurred while connecting to /ping endpoint.", ex);
}
return HealthCheckResult.Healthy("API is ready.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment