Skip to content

Instantly share code, notes, and snippets.

@benhysell
Created March 16, 2022 17:43
Show Gist options
  • Save benhysell/ccd7f086254579535262445714db59d7 to your computer and use it in GitHub Desktop.
Save benhysell/ccd7f086254579535262445714db59d7 to your computer and use it in GitHub Desktop.
c# asp.net core health check that looks at the result of the query to determine healthy or not
using System;
using System.Data.Common;
using System.Data.SqlClient;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Diagnostics.HealthChecks;
namespace YOUR_NAMESPACE_HERE
{
public class SqlExamineResultHealthCheck : IHealthCheck
{
private const string _defaultTestQuery = "Select 1";
public string ConnectionString { get; }
public string TestQuery { get; }
public SqlExamineResultHealthCheck(string connectionString)
: this(connectionString, testQuery: _defaultTestQuery)
{
}
public SqlExamineResultHealthCheck(string connectionString, string testQuery)
{
ConnectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString));
TestQuery = testQuery;
}
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default(CancellationToken))
{
var returnValue = HealthCheckResult.Healthy();
using (var connection = new SqlConnection(ConnectionString))
{
try
{
await connection.OpenAsync(cancellationToken);
if (TestQuery != null)
{
var command = connection.CreateCommand();
command.CommandText = TestQuery;
var result = await command.ExecuteScalarAsync(cancellationToken);
if(result == null || 1 != (int)result)
{
returnValue = new HealthCheckResult(status: context.Registration.FailureStatus);
}
}
}
catch (DbException ex)
{
returnValue = new HealthCheckResult(status: context.Registration.FailureStatus, exception: ex);
}
}
return returnValue;
}
}
}
services.AddHealthChecks()
.AddDbContextCheck<ApplicationDbContext>("Db Context", Microsoft.Extensions.Diagnostics.HealthChecks.HealthStatus.Unhealthy)
.AddTypeActivatedCheck<SqlExamineResultHealthCheck>("Db Stored Procedure Call", Microsoft.Extensions.Diagnostics.HealthChecks.HealthStatus.Degraded, Configuration.GetConnectionString("Connection"), @"DECLARE @return_value int
EXEC @return_value = [dbo].[CHECK_SERVER]
@pSRC_DB = 1
SELECT 'Return Value' = @return_value")
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment