DEV Community

Pongpanot Chuaysakun
Pongpanot Chuaysakun

Posted on

Add HealthCheck to ASP.Net Core API

  1. Install package
dotnet add package Microsoft.Extensions.Diagnostics.HealthChecks
Enter fullscreen mode Exit fullscreen mode
  1. Create HealthCheck class
public class SqlConnectionHealthCheck : IHealthCheck
{
    private const string DefaultTestQuery = "Select 1"; public string ConnectionString { get; }
    public string TestQuery { get; }
    public SqlConnectionHealthCheck(string connectionString) : this(connectionString, testQuery: DefaultTestQuery)
    { }
    public SqlConnectionHealthCheck(string connectionString, string testQuery)
    {
        ConnectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString));
        TestQuery = testQuery;
    }
    public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default(CancellationToken))
    {
        using (var connection = new SqlConnection(ConnectionString))
        {
            try
            {
                await connection.OpenAsync(cancellationToken);
                if (TestQuery != null)
                {
                    var command = connection.CreateCommand();
                    command.CommandText = TestQuery;
                    await command.ExecuteNonQueryAsync(cancellationToken);
                }
            }
            catch (DbException ex)
            {
                return new HealthCheckResult(status: context.Registration.FailureStatus, exception: ex);
            }
        }
        return HealthCheckResult.Healthy();
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. Configure startup.cs service
public void ConfigureServices(IServiceCollection services)
{
    services.AddHealthChecks()
            .AddCheck(
            "OrderingDB-check",
            new SqlConnectionHealthCheck(Configuration["ConnectionString"]), HealthStatus.Unhealthy,
            new string[] { "orderingdb" });
}

Enter fullscreen mode Exit fullscreen mode
  1. Map HealthCheck path
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapHealthChecks("/hc");
    });
}
Enter fullscreen mode Exit fullscreen mode

reference

Top comments (0)