Implement Health Check Middleware on Asp.NET Core 3.1 Web App
Health Checks are usually implemented by pinging resources to check if it is available, up and running. This is very important for applications with databases, microservices and APIs to ensure their availability.
In Asp.NET Core, Health Checks are provided as a middleware package. You can easily implement and check the status of your resources from an HTTP endpoint or even a beautiful UI. So how do you implement this?
Nuget Packages
Install-Package Microsoft.Extensions.Diagnostics.HealthChecks -Version 3.1.4
Install-Package Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore -Version 3.1.13
Install-Package AspNetCore.HealthChecks.SqlServer -Version 3.2.0
Install-Package AspNetCore.HealthChecks.UI -Version 3.1.3
Install-Package AspNetCore.HealthChecks.UI.Client -Version 3.1.2
Install-Package AspNetCore.HealthChecks.UI.InMemory.Storage -Version 3.1.2
Yes I know that's a lot of packages but we don't have to do much with these. Install them and let's start with Startup.cs
Here we add the HealthChecks middleware and implement checks for both the SQL server and DB Context. There is a lot more health checks available for easy implementation. You can find a list of those and related Nugets on Xabaril's Github here.
In the configure services, we also configure the UI for the Health Checks and add an in memory storage for it.
In the Configure method, we implement the routes for health checker, the UI and it's API. We also set a clean response using the UI.Client package installed.
What's next? Let's configure some custom css for the UI.
In the same configure method, we setup our custom style sheet. More on custom styling the UI is here.
Now comes the final step of the implementation and that happens in appsettings.json
Here you can set webhooks for services such as Slack, Teams and others to notify you about the degraded services and resources. More on that is here.
Once you are done implementing the middleware, you can explore:
- HealthCheck endpoint response
2. Health Checks UI
3. Health Checks UI API
And now you have a fully working health checker for your application. You can explore and implement more health checks explained in detail here. Below is the Gist with the code for Startup.cs and appsettings.json as well.
Feel free to reach out to me on Telegram if you have any doubts!