ASP.NET Core offers Health Checks Middleware and libraries for reporting the health of app infrastructure components.
Health checks are exposed by an app as HTTP endpoints. Health check endpoints can be configured for a variety of real-time monitoring scenarios:
Health probes can be used by container orchestrators and load balancers to check an app’s status. For example, a container orchestrator may respond to a failing health check by halting a rolling deployment or restarting a container. A load balancer might react to an unhealthy app by routing traffic away from the failing instance to a healthy instance.
Use of memory, disk, and other physical server resources can be monitored for healthy status.
Health checks can test an app’s dependencies, such as databases and external service endpoints, to confirm availability and normal functioning.
// HERE endpoints.MapHealthChecks("/health"); }); } }
Now, You are able to browse http://localhost:PORT/health to see Healthy!
Create health checks
Health checks are created by implementing the IHealthCheck interface. The CheckHealthAsync method returns a HealthCheckResult that indicates the health as Healthy, Degraded, or Unhealthy. The result is written as a plaintext response with a configurable status code. HealthCheckResult can also return optional key-value pairs.
The following ExampleHealthCheck class demonstrates the layout of a health check. The health checks logic is placed in the CheckHealthAsync method. The following example sets a dummy variable, healthCheckResultHealthy, to true. If the value of healthCheckResultHealthy is set to false, the HealthCheckResult.Unhealthy status is returned.
AddCheck can also execute a lambda function. In the following example, the health check name is specified as Example and the check always returns a healthy state:
Call AddTypeActivatedCheck to pass arguments to a health check implementation. In the following example, TestHealthCheckWithArgs accepts an integer and a string for use when CheckHealthAsync is called:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
publicclassTestHealthCheckWithArgs : IHealthCheck { publicTestHealthCheckWithArgs(int i, string s) { I = i; S = s; }
Represents the reported status of a health check result.
Status
Description
Degraded
It could be used for checks that did succeed but are slow or unstable. For example, A simple database query did succeed but took more than a second. Moving traffic to another instance is probably a good idea until the problem has resolved.
Healthy
Indicates that the health check determined that the component was healthy.
Unhealthy
It means that the component does not work at all. For example, A connection to the Redis cache could no be established. Restarting the instance could solve this issue.
Health Checks Routing
In Startup.Configure, call MapHealthChecks on the endpoint builder with the endpoint URL or relative path:
Call RequireHost to specify one or more permitted hosts for the health check endpoint. Hosts should be Unicode rather than punycode and may include a port. If a collection isn’t supplied, any host is accepted.
Call RequireAuthorization to run Authorization Middleware on the health check request endpoint. A RequireAuthorization overload accepts one or more authorization policies. If a policy isn’t provided, the default authorization policy is used.
By default, Health Checks Middleware runs all registered health checks. To run a subset of health checks, provide a function that returns a boolean to the Predicate option. In the following example, the Bar health check is filtered out by its tag (bar_tag) in the function’s conditional statement, where true is only returned if the health check’s Tags property matches foo_tag or baz_tag:
In Startup.Configure, the Predicate filters out the ‘Bar’ health check. Only Foo and Baz execute.:
1 2 3 4 5 6 7 8 9
app.UseEndpoints(endpoints => { endpoints.MapHealthChecks("/health", new HealthCheckOptions() { // HERE Predicate = (check) => check.Tags.Contains("foo_tag") || check.Tags.Contains("baz_tag") }); });
Suppress cache headers
AllowCachingResponses controls whether the Health Checks Middleware adds HTTP headers to a probe response to prevent response caching. If the value is false (default), the middleware sets or overrides the Cache-Control, Expires, and Pragma headers to prevent response caching. If the value is true, the middleware doesn’t modify the cache headers of the response.
// HealthCheckResult.cs // The aggregation of all health check responses, even if one is unhealthy, 'Status' will be unhealthy. publicclassHealthCheckResult { publicstring Status { get; set; } public IEnumerable<HealthCheckResponse> HealthChecks { get; set; } publicstring HealthCheckDuration { get; set; } }
ResponseWriter is responsible for how the response is displayed.
using System.Text.Json; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Http; using System.Linq;
// Only one active request will be executed at a time. // All the excedent requests will result in 429 (Too many requests) options.SetApiMaxActiveRequests(1); }) .AddInMemoryStorage(); }
HealthChecks UI JSON Settings
It is possible for you to customize your settings in appsettings.json: