Last active
April 3, 2020 02:33
-
-
Save mizrael/40dc525b78abaf18ef24823da637ea67 to your computer and use it in GitHub Desktop.
custom health check .NET Core example
This file contains hidden or 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 void Configure(IApplicationBuilder app) | |
{ | |
var healthCheckOptions = new HealthCheckOptions() | |
{ | |
ResponseWriter = WriteReadinessResponse | |
}; | |
app.UseEndpoints(endpoints => | |
{ | |
endpoints.MapHealthChecks("/ops/health", healthCheckOptions); | |
}); | |
} | |
private static Task WriteReadinessResponse(HttpContext context, HealthReport result) | |
{ | |
context.Response.ContentType = "application/json; charset=utf-8"; | |
var options = new JsonWriterOptions | |
{ | |
Indented = true | |
}; | |
using (var stream = new MemoryStream()) | |
{ | |
using (var writer = new Utf8JsonWriter(stream, options)) | |
{ | |
writer.WriteStartObject(); | |
writer.WriteString("status", result.Status.ToString()); | |
writer.WriteStartObject("results"); | |
foreach (var entry in result.Entries) | |
{ | |
writer.WriteStartObject(entry.Key); | |
writer.WriteString("status", entry.Value.Status.ToString()); | |
writer.WriteString("description", entry.Value.Description); | |
writer.WriteStartObject("data"); | |
foreach (var item in entry.Value.Data) | |
{ | |
writer.WritePropertyName(item.Key); | |
JsonSerializer.Serialize( | |
writer, item.Value, item.Value?.GetType() ?? | |
typeof(object)); | |
} | |
writer.WriteEndObject(); | |
writer.WriteEndObject(); | |
} | |
writer.WriteEndObject(); | |
writer.WriteEndObject(); | |
} | |
var json = Encoding.UTF8.GetString(stream.ToArray()); | |
return context.Response.WriteAsync(json); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment