If you’re using a load balancer in front of your ASP.NET Core application you will need to provide it a route where it can verify that your application is still running. Here’s an overview of how you can implement implement Health Checks in ASP.NET Core.
Health Checks in ASP.NET Core
If you’re using ASP.NET Core MVC, you might first think to just create a controller and action and provide that route as the health check for your load balancer.
However there are alternative ways to accomplish this with middleware.
Basic Middleware
At the very basic level, we can create a middleware high in the pipeline that is checking the request path and if /hc, return a 200 status code along with content “UP”. Here’s our Startup’s Configure method.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
At a minimum we are confirming that ASP.NET Core is running, but often times we are using databases and other external services that our web application needs to access. If our application cannot connect to these external services, do we want them to remain in the load balancer pool? If not, then we can add some various checks and return a 200 if everything is successful.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Be honest, having that database code in there is pretty awful. Let’s move this out into it’s own class and add an extension method onto IApplicationBuilder.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Now from our Configure() method we can just call the extension method.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters