7

In my work I was asked to implement health checks into an ASP.NET Web API 2 written in C#. I have searched but all the documentation is for ASP.NET Core and its implementation, does anyone know how to implement health check featurs in the classic / full .NET Framework?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Camilo Garcia
  • 81
  • 1
  • 5
  • 1
    Probably create a dummy reachable end point that also tests dependent external resources (like database connections). Then create some external event (recurring and/or manually triggered) that tests this end point and reports results. – Igor Jun 12 '20 at 19:45
  • app.metrics has healthchecks. – Daniel A. White Jun 12 '20 at 20:17

1 Answers1

7

I agree with Igor. Here's a concrete application of what he suggested (obviously, there are other ways to do this, but this is the best way I know how to keep it clear and honor separation of concerns):

  1. Create a new controller. In this example, I'll call it HealthController
  2. Add an action to the controller, and annotate it with [HttpGet]
  3. Place logic inside the action that checks for the stability of external dependencies. For example, if disk access is critical for your API, run a test or two to make sure that the disk is responding like you need it to. If you need to be able to query a database, make a sample query, and make sure it's successful. This part is completely custom and really depends on your API and how it needs to perform.
public class HealthController : ApiController
{
    [HttpGet]
    public IHttpActionResult Check()
    {
        // Add logic here to check dependencies
        if (/* successful */)
        {
            return Ok();
        }

        return InternalServerError(); // Or whatever other HTTP status code is appropriate
    }
}
  1. Have an external service issue a GET request to your endpoint (currently at https://whatever.your.domain.is/Health/Check) and report back when it doesn't receive 200 OK for some amount of time.

I've used Amazon CloudWatch in the past and I've been happy with it. There are going to be other services out there that will do this for you, but I don't have any experience with them.

techfooninja
  • 165
  • 10