Take advantage of health check middleware in ASP.Net Core to monitor the health of your application, its database connection, and more Credit: Gerd Altmann Health checks are used to determine if the application is responding to requests normally. ASP.Net Core provides support for health checks for reporting the health of an application using health check middleware, which was introduced in ASP.Net Core 2.2. Health checks in ASP.Net Core are exposed as HTTP endpoints and are configurable. You can use health checks to do a basic check for liveness, to check system or network resources, to check whether the database is responding, or to check on other dependencies such as a message broker or an Azure cloud service. This article presents a discussion of how we can work with the health check middleware in ASP.Net Core. Create an ASP.Net Core project in Visual Studio First off, let’s create an ASP.Net Core project. If Visual Studio 2017 is up and running in your system, follow the steps given below to create a new ASP.Net Core project in Visual Studio. Launch the Visual Studio 2017 IDE. Click on File > New > Project. Select “ASP.Net Core Web Application (.Net Core)” from the list of the templates displayed. Specify a name for the project. Click OK to save the project. A new window “New .Net Core Web Application…” is shown next. Select .Net Core as the runtime and ASP.Net Core 2.2 (or later) from the drop-down list at the top. Select API as the project template. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here. Ensure that “No Authentication” is selected as we won’t be using authentication either. Click OK. This will create a new ASP.Net Core project in Visual Studio. We’ll use this project in the subsequent sections of this article. Register health check services in ASP.Net Core To register health check services, you should call the AddHealthChecks method in the ConfigureServices method of the Startup class. Next, you should add the health check middleware by calling the UseHealthChecks as shown in the code snippet below. public void ConfigureServices(IServiceCollection services) { services.AddHealthChecks(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseHealthChecks("/health"); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseMvc(); } Note that both the ConfigureServices and Configure methods are called by the runtime. Built-in health checks in ASP.Net Core You can take advantage of the built-in Entity Framework Core DbContext health check to report if the Entity Framework Core DbContext is able to connect to the database. To do this, you should add the Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore NuGet package and configure health checks in the ConfigureServices method as shown below. services.AddHealthChecks().AddDbContextCheck<MyDbContext> ("IDGDbContextHealthCheck"); You can also leverage other health check packages available in NuGet if need be. These include SQL Server, MySQL, MongoDB, Redis, RabbitMQ, Elasticsearch, Hangfire, Kafka, Oracle, Azure Storage, and more. These community packages are available in the AspNetCore.Diagnostics.HealthChecks repository on GitHub. Create custom health checks in ASP.Net Core You can build custom health checks to verify and report if the application is unable to connect to the database or an external service, for example. To create a custom health check, you should extend the IHealthCheck interface and implement the CheckHealthAsync method. public class MyCustomHealthCheck : IHealthCheck { public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default(CancellationToken)) { throw new System.NotImplementedException(); } } Here’s how you can implement the CheckHealthAsync method. Note how the HealthCheckResult struct has been used in this method. public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default(CancellationToken)) { bool canConnect = IsDBOnline(); if (canConnect) return HealthCheckResult.Healthy(); return HealthCheckResult.Unhealthy(); } The IsDBOnline method checks if the database is up and running. private bool IsDBOnline() { string connectionString = "some connection string to connect to the database"; try { using (SqlConnection connection = new SqlConnection(connectionString)) { if (connection.State != System.Data.ConnectionState.Open) connection.Open(); } return true; } catch (System.Exception) { return false; } } Here is the complete code listing for your reference. using Microsoft.Extensions.Diagnostics.HealthChecks; using System.Threading; using System.Threading.Tasks; namespace IDGHealthCheckApp { public class MyCustomHealthCheck : IHealthCheck { public async Task CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default(CancellationToken)) { bool canConnect = IsDBOnline(); if (canConnect) return HealthCheckResult.Healthy(); return HealthCheckResult.Unhealthy(); } private bool IsDBOnline() { string connectionString = "some connection string to connect to the database"; try { using (SqlConnection connection = new SqlConnection(connectionString)) { if (connection.State != System.Data.ConnectionState.Open) connection.Open(); } return true; } catch (System.Exception) { return false; } } } } The HealthCheckResult object shown in the code snippet above enables us to pass description, exception, and status data represented as a dictionary of key-value pairs. This information can then be presented in the health check web page. Once your custom health check is built, you should configure the custom health check type appropriately in the ConfigureServices and Configure methods of the Startup class to start leveraging it. Visualizing health checks in ASP.Net Core If you would like to visualize the health check in a better way, you can take advantage of an open source visualization tool named HealthChecksUI. To use this tool, install it from NuGet by using the following command at the package manager console window. Install-Package AspNetCore.HealthChecks.UI Once the package has been installed, you should configure it in the ConfigureServices and Configure methods of the Startup class. public void ConfigureServices(IServiceCollection services) { services.AddHealthChecksUI(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseHealthChecks("/health", new HealthCheckOptions { Predicate = _ => true, ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse }); app.UseHealthChecksUI(); } That’s not all. You should also add the following configuration in the appsettings.json file to let HealthChecksUI know where to fetch the health check information. "HealthChecks-UI": { "HealthChecks": [ { "Name": "Local", "Uri": "http://localhost:1994/health" } ], "EvaluationTimeOnSeconds": 10, "MinimumSecondsBetweenFailureNotifications": 60 } Finally, start your application and navigate to /healthchecks-ui to monitor its health. IDG HealthChecksUI in action. The health check middleware in ASP.Net Core makes it is easy to add and configure health checks of system resources, databases, and other services your application depends on. It is up to you to determine what is considered healthy and what is considered unhealthy, and to configure how the health check endpoint should respond. You can even send out failure notifications when a health check fails—such as when your application is unable to connect to the database. Related content feature 14 great preprocessors for developers who love to code Sometimes it seems like the rules of programming are designed to make coding a chore. Here are 14 ways preprocessors can help make software development fun again. By Peter Wayner Nov 18, 2024 10 mins Development Tools Software Development feature Designing the APIs that accidentally power businesses Well-designed APIs, even those often-neglected internal APIs, make developers more productive and businesses more agile. By Jean Yang Nov 18, 2024 6 mins APIs Software Development news Spin 3.0 supports polyglot development using Wasm components Fermyon’s open source framework for building server-side WebAssembly apps allows developers to compose apps from components created with different languages. By Paul Krill Nov 18, 2024 2 mins Microservices Serverless Computing Development Libraries and Frameworks news Go language evolving for future hardware, AI workloads The Go team is working to adapt Go to large multicore systems, the latest hardware instructions, and the needs of developers of large-scale AI systems. By Paul Krill Nov 15, 2024 3 mins Google Go Generative AI Programming Languages Resources Videos