Created
June 28, 2018 21:04
-
-
Save dcomartin/184b5c2b09bc23e66a4e30ca3ea6817c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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