SQL Database Health check in ASP.NET core

In this article we will understand how to add a health check for SQL server database from .NET core web api application.

In this article we will perform below activities.

  1. Create a .NET core web api application.

  2. Create an Employee table in azure SQL database

  3. Create an Employee model class

  4. Create a new controller.

  5. Build and run the application. Invoke the api and add an employee.

Now we have an application which depends on SQL DB. This application is said to be helathy if the application can connect to SQL DB. Let's add a health check to verify the connectivity of the SQL DB

  1. We have a package "AspNetCore.HealthChecks.SqlServer" available to check the health of SQL server DB.

    Install the package using the command dotnet add package AspNetCore.HealthChecks.SqlServer

  2. I am using azure keyvault to save the secrets. The secret identifiers are configured in appsettings file
  3. Fetch the SQL DB connection string in the Program.cs file as shown below
  4. Add SQL server health check using the "AddSqlServer" extension method as shown below. Passing the previously fetched connection string as input parameter
  5. Add a health check endpoint in the Program.cs file
  6. Run the application and navigate to "healthz" endpoint
  7. I am running the application locally and I am using Azure SQL DB. So to be able to connnect to azure SQL DB from local, I need to add a firewall rule to allow my client IP as shown below. Let's verify the unhealthy scenario by removing the firewall rule or we can also verify by giving the wrong connection string
  8. Run the application and navigate to "healthz" endpoint

In this article we have learnt about adding health check for SQL DB in .NET core application. Let me know your thoughts in the comments.
The github repo link for the code changes made in this article is here