- Install package
dotnet add package Microsoft.Extensions.Diagnostics.HealthChecks
- 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();
}
}
- Configure startup.cs service
public void ConfigureServices(IServiceCollection services)
{
services.AddHealthChecks()
.AddCheck(
"OrderingDB-check",
new SqlConnectionHealthCheck(Configuration["ConnectionString"]), HealthStatus.Unhealthy,
new string[] { "orderingdb" });
}
- Map HealthCheck path
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
app.UseEndpoints(endpoints =>
{
endpoints.MapHealthChecks("/hc");
});
}
reference
Top comments (0)