Implementing Health Checks in .NET

Introduction

Ensuring the health and reliability of your applications is important for minimizing lost revenue and maximizing the user experience.

By adding health checks to your application, you can continuously monitor the pulse of applications, assess vital signs, and preemptively detect anomalies before they become critical issues. Whether its database connectivity, external dependencies, or other custom application-specific checks, health checks provide you with a comprehensive and proactive view of an application’s well-being.

In this blog, I’ll delve into the world of health checks in .NET, exploring what they are, why they matter, and how to implement them effectively.

Why Health Checks Matter

Health checks offer several benefits to developers, users, and operations teams:

  1. Proactive Monitoring: Health checks enable proactive monitoring of application components, helping teams identify and resolve issues before they impact end-users.
  2. Improved Reliability: By continuously assessing the health of your application, you can maintain high reliability and uptime, thereby enhancing user experience and trust.
  3. Faster Troubleshooting: Health checks provide valuable insights into the root causes of potential problems, enabling teams to troubleshoot and resolve issues more efficiently.
  4. Automated Remediation: When integrated with automated alerting and remediation systems, health checks can trigger automatic responses to resolve issues, reducing manual intervention and downtime.

Implementing Health Checks in .NET

In the .NET ecosystem, implementing health checks is straightforward, thanks to built-in support provided by frameworks like ASP.NET Core. Let’s explore how you can integrate health checks into your ASP.NET CORE applications with the Health Checks Middleware:

1. Using ASP.NET Core Health Checks Middleware

ASP.NET Core provides a powerful Health Checks Middleware that allows you to define custom health checks for your application. Here’s a basic example of how to set up health checks in an ASP.NET Core application:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHealthChecks();

var app = builder.Build();
app.MapHealthChecks("/healthz");

app.Run();

Or, if you’re still using the older style Startup.cs in your ASP.NET Core project:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHealthChecks();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseHealthChecks("/healthz");
}

In this example, we’ve added the Health Checks Middleware to our application pipeline and specified the endpoint (“/healthz”) where health check results will be exposed.

Note: Metadata endpoints like this often use a “z” as a suffix to help ensure there is no collision with similarly-named endpoints exposed by the application itself.

2. Implementing Custom Health Checks

You can also create custom health checks tailored to your application’s specific requirements. Here’s how you can define a custom health check in .NET:

public class CustomHealthCheck : IHealthCheck
{
    public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
    {
        // Perform health check logic here
        bool isHealthy = true; // Example health check logic

        if (isHealthy)
        {
            return Task.FromResult(HealthCheckResult.Healthy("Custom check is healthy."));
        }
        else
        {
            return Task.FromResult(HealthCheckResult.Unhealthy("Custom check is unhealthy."));
        }
    }
}

In this example, we’ve implemented the IHealthCheck interface and overridden the CheckHealthAsync method to perform custom health check logic. Depending on the result of the health check, we return either a Healthy or Unhealthy status along with an optional description.

3. Monitoring External Dependencies

You can also use health checks to monitor external dependencies such as databases, APIs, and services. ASP.NET Core provides built-in health check probes for common dependencies like SQL Server, Redis, and Azure Service Bus.

public class DatabaseHealthCheck : IHealthCheck
{
    private readonly string _connectionString;

    public DatabaseHealthCheck(IConfiguration configuration)
    {
        _connectionString = configuration.GetConnectionString("DefaultConnection");
    }

    public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
    {
        try
        {
            using (var connection = new SqlConnection(_connectionString))
            {
                await connection.OpenAsync(cancellationToken);

                if (connection.State == System.Data.ConnectionState.Open)
                {
                    return HealthCheckResult.Healthy("Database connection is healthy.");
                }
                else
                {
                    return HealthCheckResult.Unhealthy("Database connection is not open.");
                }
            }
        }
        catch (Exception ex)
        {
            return HealthCheckResult.Unhealthy("Exception during database connection: " + ex.Message);
        }
    }
}

Next Steps

Once health checks are implemented as an endpoint in your application, they will need to be monitored from a central location or system to be useful. This process is commonly referred to as “health check monitoring” or “health monitoring.” It involves regularly checking the results of your health checks to ensure that all components of the application are functioning as expected.

Azure Application Insights is one of the services available to you that will do just that. It allows you to monitor the availability, performance, and usage of your web applications and services through endpoints you configure. Within Application Insights, you can set up different availability tests that periodically check the health of your application, even from different geographic locations. You can then use its robust alerting system to let the right groups know when there is an issue.

Conclusion

Health checks are a fundamental aspect of modern application development, providing invaluable insights into the operational state and reliability of your applications. By implementing health checks in your .NET applications, you can proactively monitor critical components, ensure high availability, and deliver a seamless user experience.

In this guide, we’ve explored the importance of health checks, their benefits, and how to implement them effectively using ASP.NET. By incorporating health checks into your development workflow, you can build robust, reliable, and resilient applications that meet the demands of today’s dynamic software landscape.

If you’d like help setting up health checks in your application, Trailhead can help with that. Just contact us to get the process started.

Picture of Aleksandar Dickov

Aleksandar Dickov

Aleksandar is a seasoned professional with a decade of experience in software development. He holds a B.S. in Computer Science from the Faculty of Technical Science. Throughout his career, he has actively contributed to the creation of web and desktop applications, acquiring proficiency in languages such as C# and a strong command of the .NET platform. Thriving on the challenge of solving complex problems, Aleksandar is known for his result-oriented approach and unwavering dedication to delivering impactful solutions. His passion for software development extends beyond the professional realm, believing in the continuous pursuit of knowledge to enhance his contributions to any team. Beyond the world of coding, Aleksandar finds joy in basketball, football, and skiing. Whether it's exploring new places, engaging in sports, or maintaining a blog, he embraces a well-rounded approach to life.

Free Consultation

Sign up for a FREE consultation with one of Trailhead's experts.

"*" indicates required fields

This field is for validation purposes and should be left unchanged.

Related Blog Posts

We hope you’ve found this to be helpful and are walking away with some new, useful insights. If you want to learn more, here are a couple of related articles that others also usually find to be interesting:

Our Gear Is Packed and We're Excited to Explore With You

Ready to come with us? 

Together, we can map your company’s software journey and start down the right trails. If you’re set to take the first step, simply fill out our contact form. We’ll be in touch quickly – and you’ll have a partner who is ready to help your company take the next step on its software journey. 

We can’t wait to hear from you! 

Main Contact

This field is for validation purposes and should be left unchanged.

Together, we can map your company’s tech journey and start down the trails. If you’re set to take the first step, simply fill out the form below. We’ll be in touch – and you’ll have a partner who cares about you and your company. 

We can’t wait to hear from you! 

Montage Portal

Montage Furniture Services provides furniture protection plans and claims processing services to a wide selection of furniture retailers and consumers.

Project Background

Montage was looking to build a new web portal for both Retailers and Consumers, which would integrate with Dynamics CRM and other legacy systems. The portal needed to be multi tenant and support branding and configuration for different Retailers. Trailhead architected the new Montage Platform, including the Portal and all of it’s back end integrations, did the UI/UX and then delivered the new system, along with enhancements to DevOps and processes.

Logistics

We’ve logged countless miles exploring the tech world. In doing so, we gained the experience that enables us to deliver your unique software and systems architecture needs. Our team of seasoned tech vets can provide you with:

Custom App and Software Development

We collaborate with you throughout the entire process because your customized tech should fit your needs, not just those of other clients.

Cloud and Mobile Applications

The modern world demands versatile technology, and this is exactly what your mobile and cloud-based apps will give you.

User Experience and Interface (UX/UI) Design

We want your end users to have optimal experiences with tech that is highly intuitive and responsive.

DevOps

This combination of Agile software development and IT operations provides you with high-quality software at reduced cost, time, and risk.

Trailhead stepped into a challenging project – building our new web architecture and redeveloping our portals at the same time the business was migrating from a legacy system to our new CRM solution. They were able to not only significantly improve our web development architecture but our development and deployment processes as well as the functionality and performance of our portals. The feedback from customers has been overwhelmingly positive. Trailhead has proven themselves to be a valuable partner.

– BOB DOERKSEN, Vice President of Technology Services
at Montage Furniture Services

Technologies Used

When you hit the trails, it is essential to bring appropriate gear. The same holds true for your digital technology needs. That’s why Trailhead builds custom solutions on trusted platforms like .NET, Angular, React, and Xamarin.

Expertise

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

  • Project Management
  • Architecture
  • Web App Development
  • Cloud Development
  • DevOps
  • Process Improvements
  • Legacy System Integration
  • UI Design
  • Manual QA
  • Back end/API/Database development

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

Our Gear Is Packed and We're Excited to Explore with You

Ready to come with us? 

Together, we can map your company’s tech journey and start down the trails. If you’re set to take the first step, simply fill out the contact form. We’ll be in touch – and you’ll have a partner who cares about you and your company. 

We can’t wait to hear from you! 

Thank you for reaching out.

You’ll be getting an email from our team shortly. If you need immediate assistance, please call (616) 371-1037.