Reputation: 111
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 features in the classic / full .NET Framework?
Upvotes: 10
Views: 11805
Reputation: 195
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):
HealthController
[HttpGet]
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
}
}
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.
Upvotes: 8
Reputation: 32576
The Microsoft.Extensions.Diagnostic.HealthChecks
packages are compatible with .Net Framework and can be used as per the existing documentation. The missing piece is just a handler to handle requests to the endpoint and run the health checks.
I've recently implemented health checks in an application targeting net472
as follows:
IHealthCheck
as documented for an ASP.Net Core application.public class HealthCheckHandler : OwinMiddleware
{
private readonly HealthCheckService _healthCheckService;
public HealthCheckHandler(OwinMiddleware next, HealthCheckService healthCheckService)
: base(next)
{
_healthCheckService = healthCheckService;
}
public override async Task Invoke(IOwinContext context)
{
var report = await _healthCheckService.CheckHealthAsync(context.Request.CallCancelled);
if (report.Status == HealthStatus.Unhealthy)
{
context.Response.StatusCode = (int)HttpStatusCode.ServiceUnavailable;
}
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(report.ToJsonString());
}
}
var services = new ServiceCollection();
services.AddHealthChecks().AddCheck<MyHealthCheck>(MyCheck);
builder.Populate(services);
That last method is in the Autofac.Extensions.DependencyInjection
package.Microsoft.Extensions.Diagnostics.HealthChecks.HealthCheckService
from the DI container and then call :
app.Map("/health", x => x.Use(typeof(HealthCheckHandler), healthCheckService));
Upvotes: 1