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.
Sponsor: Do you build complex software systems? See how NServiceBus makes it easier to design, build, and manage software systems that use message queues to achieve loose coupling. Get started for free.
Health Checks in ASP.NET CoreIf 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 MiddlewareAt 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.
Checking ServicesAt 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.
RefactorBe 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. Now from our
Configure()method we can just call the extension method.