I have a scenario where I have to call API periodically to receive health status.
what if I use a while use?
while (true)
{
// API call
var health = _client.GetHealth(1).Result;
if (health)
{
some other work
}
Thread.Sleep(2000);
}
This is already available through the Health Checks middleware. The health checks service will check the registered probes periodically to see if everything is OK. The health status can be logged or exposed through an API endpoint.
There are several probes available. The open source AspNetCore.Diagnostics.HealthChecks library offers probes from everything from remote APIs to various database products, cloud services and more. It also offers a Health check dashboard that displays detailed health check history.
Using Health Checks is easy, as it's already included in the web app templates.
Registering it requires adding the following to Startup.cs
:
public void ConfigureServices(IServiceCollection services)
{
services.AddHealthChecks();
}
public void Configure(IApplicationBuilder app)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapHealthChecks("/health");
});
}
MapHealthChecks
exposes a basic status at /health
endpoint. To check a remote API you can add the AspNetCore.HealthChecks.Uris
package and use one of the AddUrlGroup overloads:
public void ConfigureServices(IServiceCollection services)
{
services.AddHealthChecks()
.AddUrlGroup(new Uri("http://httpbin.org/status/200"));
}