How to check health of application in .NET Core

Introduction

Health checks are used to check overall health and availability of our application infrastructure. These checks are exposed by an app as HTTP endpoints.

Whenever a health check fails , we can implement some notifications e.g. email to keep us posted about issues. Health check endpoints can be configured for various real-time monitoring scenarios.

Different types of health checks

We have different types of health checks that serve different purpose :

  • Check dependencies
  • Databases connections
  • External endpoints
  • Monitor memory, disk and physical server resources

Level of health checks explained

Health checks have three levels :

  1. Healthy :- Everything is working fine in our app

  2. Unhealthy :- Some checks is being failed or throwing unhandled exception

  3. Degraded :- Application is responding but taking more time than expected

How to implement them in .NET 6

Install this Nuget Package before moving forward

AspNetCore.HealthChecks.UI.Client

  1. Step 1 : Configure Program.cs , app.MapHealthChecks(“/health”) add this code after app.UseHttpsRedirection();

How to check health of application in .NET Core

ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse

This line displays a proper formatted response to user , let’s see in next section

  1. Step 2 : Register dependency of your checks (Either custom or built in )

How to create your custom checks

  1. Step 1 : Create a class inheriting IHealthCheck and implement its method CheckHealthAsync CustomHealthCheck.cs

How to check health of application in .NET Core

  1. Step 2 : Register your check in Program.cs , I have registered Custom check and some dummy checks as well to demonstrate that on same fashion we can add multiple checks as well.

How to check health of application in .NET Core

Let’s test it via Postman :

How to check health of application in .NET Core

How to implement health checks for third parties

We have bunch of libraries available that serve different purpose , if you don’t like creating custom checks you can use built in as well.

How to check health of application in .NET Core

Search your desired package and implement it you have to just add the name of package and provide it configurations if applicable (like connection strings).

There are still few things in this topic to cover , like :

  • Adding a dashboard
  • Defining CORS and authorization
  • Proper implementation of SQL custom health check

You can explore it here or if you want to me to cover those respond this email.

This article was originally published at https://mwaseemzakir.substack.com/ on .

Whenever you're ready, there are 3 ways I can help you:

  1. Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
  2. Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
  3. Patreon community : Get access to all of my blogs and articles at one place