I am working on a application that checks the health status of external services (API's etc). To display the health statuses I need make an API call for every service there is.
I am having trouble retrieving the result of the API calls using asynchronous functions.
I have two methods to retrieve the information of the API endpoints. But I can't figure out why it is not working.
public async Task<List<HealthStatus>> ExecuteApiCallsAsync()
{
var apis = new[] {
new { Name = "API 1", Url = "https://localhost:7157/api/healthstatus" },
new { Name = "API 2", Url = "https://localhost:7150/api/healthstatus" }
};
var tasks = new List<Task<HealthStatus>>();
try
{
// for(int i = 0; i < apis.Length; i++)
// {
// //tasks[i] = GetApiHealthStatusAsync(apis[i].Name, apis[i].Url);
// //tasks.Add(GetApiHealthStatusAsync(api.Name, api.Url));
// }
foreach (var api in apis)
{
tasks.Add(GetApiHealthStatusAsync(api.Name, api.Url));
}
Task.WaitAll(tasks.ToArray());
return tasks.ToList();
}
catch (Exception ex)
{
}
}
public async Task<HealthStatus> GetApiHealthStatusAsync(string apiName, string apiUrl)
{
var healthStatus = new HealthStatus { Name = apiName };
try
{
using var client = new HttpClient();
var result = await client.GetAsync(apiUrl);
if (result != null && result.IsSuccessStatusCode)
{
var content = await result.Content.ReadAsStringAsync();
healthStatus = JsonConvert.DeserializeObject<HealthStatus>(content);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
healthStatus.Condition = "Unhealthy";
}
return healthStatus;
}