Last active
July 13, 2020 13:29
-
-
Save vitaliitylyk/910c89b13c37fa8052a822a35ecfe05b to your computer and use it in GitHub Desktop.
A custom health check which checks internal API endpoints. More information: https://blog.vitaliitylyk.com/sitecore-9-3-health-checks/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Net.Http; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using Microsoft.Extensions.Diagnostics.HealthChecks; | |
using Sitecore.Abstractions; | |
namespace HealthChecks | |
{ | |
public class ApiHealthCheck : IHealthCheck | |
{ | |
private static readonly HttpClient httpClient = new HttpClient(); | |
private static readonly Uri localhostUri = new Uri("http://localhost"); | |
private readonly BaseSettings settings; | |
private static IEnumerable<Uri> uris; | |
public ApiHealthCheck(BaseSettings settings) | |
{ | |
this.settings = settings; | |
} | |
private IEnumerable<Uri> Uris | |
{ | |
get | |
{ | |
if (uris != null) | |
{ | |
return uris; | |
} | |
uris = settings | |
.GetPipedListSetting("HealthChecks.Api.Endpoints", Array.Empty<string>()) | |
.Select(x => x.Trim()) | |
.Where(x => !string.IsNullOrEmpty(x)) | |
.Select(x => new Uri(localhostUri, x)); | |
return uris; | |
} | |
} | |
public async Task<HealthCheckResult> CheckHealthAsync( | |
HealthCheckContext context, | |
CancellationToken cancellationToken = default) | |
{ | |
foreach (var uri in Uris) | |
{ | |
try | |
{ | |
var responeMessage = await httpClient.GetAsync(uri, cancellationToken).ConfigureAwait(false); | |
responeMessage.EnsureSuccessStatusCode(); | |
} | |
catch (Exception ex) | |
{ | |
return HealthCheckResult.Unhealthy($"Endpoint {uri} has returned unsuccessful status code", ex); | |
} | |
} | |
return HealthCheckResult.Healthy(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment