Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 33 additions & 10 deletions src/Web/HealthChecks/ApiHealthCheck.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,48 @@ namespace Microsoft.eShopWeb.Web.HealthChecks;
public class ApiHealthCheck : IHealthCheck
{
private readonly BaseUrlConfiguration _baseUrlConfiguration;
private readonly IHttpClientFactory _httpClientFactory;

public ApiHealthCheck(IOptions<BaseUrlConfiguration> baseUrlConfiguration)
public ApiHealthCheck(
IOptions<BaseUrlConfiguration> baseUrlConfiguration,
IHttpClientFactory httpClientFactory)
{
_baseUrlConfiguration = baseUrlConfiguration.Value;
_httpClientFactory = httpClientFactory;
}

public async Task<HealthCheckResult> CheckHealthAsync(
HealthCheckContext context,
CancellationToken cancellationToken = default(CancellationToken))
CancellationToken cancellationToken = default)
{
string myUrl = _baseUrlConfiguration.ApiBase + "catalog-items";
var client = new HttpClient();
var response = await client.GetAsync(myUrl);
var pageContents = await response.Content.ReadAsStringAsync();
if (pageContents.Contains(".NET Bot Black Sweatshirt"))
try
{
return HealthCheckResult.Healthy("The check indicates a healthy result.");
}
var client = _httpClientFactory.CreateClient();
var url = $"{_baseUrlConfiguration.ApiBase}catalog-items";

var response = await client.GetAsync(url, cancellationToken);

if (!response.IsSuccessStatusCode)
{
return HealthCheckResult.Unhealthy(
$"API returned {response.StatusCode}");
}

var content = await response.Content.ReabdAsStringAsync(cancellationToken);

return HealthCheckResult.Unhealthy("The check indicates an unhealthy result.");
if (content.Contains(".NET Bot Black Sweatshirt"))
{
return HealthCheckResult.Healthy(
"The check indicates a healthy result.");
}

return HealthCheckResult.Unhealthy(
"The check indicates an unhealthy result.");
}
catch (Exception ex)
{
return HealthCheckResult.Unhealthy(
"API health check failed.", ex);
}
}
}