How to implement health checks in ASP.NET Core
By FoxLearn 1/4/2025 2:11:56 AM 216
Introduced in ASP.Net Core 2.2, health checks are exposed as configurable HTTP endpoints. You can define what constitutes a healthy or unhealthy state and configure the health check endpoint's response.
Register health check services in ASP.NET Core
To register health check services, use the AddHealthChecks
method in the ConfigureServices
method of the Startup
class. Then, add the health check middleware by calling UseHealthChecks
as shown in the example below:
public void ConfigureServices(IServiceCollection services) { services.AddHealthChecks(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseHealthChecks("/health"); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseMvc(); }
Remember, both the ConfigureServices
and Configure
methods are invoked by the runtime.
Built-in health checks in ASP.NET Core
You can use the built-in Entity Framework Core DbContext health check to verify if the DbContext can connect to the database.
For example, to check the health of a BlogDbContext
, you would configure the health check in the ConfigureServices
method as follows:
services.AddHealthChecks().AddDbContextCheck<BlogDbContext>("BlogDbContextHealthCheck");
You can use various community-supported health check packages from NuGet for systems like SQL Server, MySQL, MongoDB, Redis, RabbitMQ, Elasticsearch, Hangfire, Kafka, Oracle, Azure Storage, and more.
Create custom health checks in ASP.NET Core
You can create custom health checks to monitor specific services like a database or external service. To do this, implement the IHealthCheck
interface and define the CheckHealthAsync
method.
public class MyCustomHealthCheck : IHealthCheck { public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default) { throw new System.NotImplementedException(); } }
In the CheckHealthAsync
method, you will use the HealthCheckResult
struct to report the health status of the service.
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default) { bool canConnect = IsDBOnline(); if (canConnect) return HealthCheckResult.Healthy(); return HealthCheckResult.Unhealthy(); } private bool IsDBOnline() { string connectionString = "your connection string here"; try { using (SqlConnection connection = new SqlConnection(connectionString)) { if (connection.State != System.Data.ConnectionState.Open) connection.Open(); } return true; } catch (Exception) { return false; } }
In this example, the IsDBOnline
method checks if the database can be accessed by attempting to open a connection. If successful, the health check returns Healthy
, otherwise Unhealthy
.
The HealthCheckResult
object allows you to include description, exception, and status data as key-value pairs, which can be displayed on the health check web page. After creating a custom health check, you need to configure it in the ConfigureServices
and Configure
methods of the Startup
class to begin using it.
Visualizing health checks in ASP.NET Core
To visualize health checks more effectively, you can use the open-source tool HealthChecksUI.
First, install the package from NuGet with the command:
Install-Package AspNetCore.HealthChecks.UI
Then, configure it in the ConfigureServices
and Configure
methods of the Startup
class:
public void ConfigureServices(IServiceCollection services) { services.AddHealthChecksUI(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseHealthChecks("/health", new HealthCheckOptions { Predicate = _ => true, ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse }); app.UseHealthChecksUI(); }
You also need to configure the appsettings.json
to specify where HealthChecksUI will fetch health data:
"HealthChecks-UI": { "HealthChecks": [ { "Name": "Local", "Uri": "http://localhost:1811/health" } ], "EvaluationTimeOnSeconds": 10, "MinimumSecondsBetweenFailureNotifications": 60 }
After setting up, start your application and navigate to /healthchecks-ui
to monitor its health.
The health check middleware in ASP.Net Core simplifies the process of adding and configuring health checks for system resources, databases, and other services. You can define what constitutes a healthy or unhealthy state and configure the health check endpoint's response.
- Options Pattern In ASP.NET Core
- Implementing Rate Limiting in .NET
- IExceptionFilter in .NET Core
- Repository Pattern in .NET Core
- CRUD with Dapper in ASP.NET Core
- How to Implement Mediator Pattern in .NET
- How to use AutoMapper in ASP.NET Core
- How to fix 'asp-controller and asp-action attributes not working in areas'