Instantly share code, notes, and snippets.

Embed
What would you like to do?
public class HealthCheckMiddleware
{
private readonly RequestDelegate _next;
private readonly string _path;
public HealthCheckMiddleware(RequestDelegate next, string path)
{
_next = next;
_path = path;
}
public async Task InvokeAsync(HttpContext context)
{
if (context.Request.Path.Value == _path)
{
try
{
using (var db = new SqlConnection("Database=Oops"))
{
await db.OpenAsync();
db.Close();
}
context.Response.StatusCode = 200;
context.Response.ContentLength = 2;
await context.Response.WriteAsync("UP");
}
catch (SqlException)
{
context.Response.StatusCode = 400;
context.Response.ContentLength = 20;
await context.Response.WriteAsync("SQL Connection Error");
}
}
else
{
await this._next(context);
}
}
}
public static class HealthCheckMiddlewareExtensions
{
public static IApplicationBuilder UseHealthCheck(this IApplicationBuilder builder, string path)
{
return builder.UseMiddleware<HealthCheckMiddleware>(path);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment