Skip to content

Commit c407fc4

Browse files
authored
Health Checks sample 3.1 updates (dotnet#16204)
1 parent dcd40d4 commit c407fc4

File tree

9 files changed

+83
-47
lines changed

9 files changed

+83
-47
lines changed

aspnetcore/host-and-deploy/health-checks.md

Lines changed: 15 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ description: Learn how to set up health checks for ASP.NET Core infrastructure,
55
monikerRange: '>= aspnetcore-2.2'
66
ms.author: riande
77
ms.custom: mvc
8-
ms.date: 11/13/2019
8+
ms.date: 12/15/2019
99
uid: host-and-deploy/health-checks
1010
---
1111
# Health checks in ASP.NET Core
@@ -294,9 +294,7 @@ app.UseEndpoints(endpoints =>
294294

295295
### Customize output
296296

297-
The <xref:Microsoft.AspNetCore.Diagnostics.HealthChecks.HealthCheckOptions.ResponseWriter> option gets or sets a delegate used to write the response.
298-
299-
In `Startup.Configure`:
297+
In `Startup.Configure`, set the [HealthCheckOptions.ResponseWriter](xref:Microsoft.AspNetCore.Diagnostics.HealthChecks.HealthCheckOptions.ResponseWriter) option to a delegate for writing the response:
300298

301299
```csharp
302300
app.UseEndpoints(endpoints =>
@@ -308,27 +306,19 @@ app.UseEndpoints(endpoints =>
308306
});
309307
```
310308

311-
The default delegate writes a minimal plaintext response with the string value of [HealthReport.Status](xref:Microsoft.Extensions.Diagnostics.HealthChecks.HealthReport.Status). The following custom delegate, `WriteResponse`, outputs a custom JSON response:
309+
The default delegate writes a minimal plaintext response with the string value of [HealthReport.Status](xref:Microsoft.Extensions.Diagnostics.HealthChecks.HealthReport.Status). The following custom delegates output a custom JSON response.
312310

313-
```csharp
314-
private static Task WriteResponse(HttpContext httpContext, HealthReport result)
315-
{
316-
httpContext.Response.ContentType = "application/json";
311+
The first example from the sample app demonstrates how to use <xref:System.Text.Json?displayProperty=fullName>:
317312

318-
var json = new JObject(
319-
new JProperty("status", result.Status.ToString()),
320-
new JProperty("results", new JObject(result.Entries.Select(pair =>
321-
new JProperty(pair.Key, new JObject(
322-
new JProperty("status", pair.Value.Status.ToString()),
323-
new JProperty("description", pair.Value.Description),
324-
new JProperty("data", new JObject(pair.Value.Data.Select(
325-
p => new JProperty(p.Key, p.Value))))))))));
326-
return httpContext.Response.WriteAsync(
327-
json.ToString(Formatting.Indented));
328-
}
329-
```
313+
[!code-csharp[](health-checks/samples/3.x/HealthChecksSample/CustomWriterStartup.cs?name=snippet_WriteResponse_SystemTextJson)]
330314

331-
The health checks system doesn't provide built-in support for complex JSON return formats because the format is specific to your choice of monitoring system. Feel free to customize the `JObject` in the preceding example as necessary to meet your needs.
315+
The second example demonstrates how to use [Newtonsoft.Json](https://www.nuget.org/packages/Newtonsoft.Json/):
316+
317+
[!code-csharp[](health-checks/samples/3.x/HealthChecksSample/CustomWriterStartup.cs?name=snippet_WriteResponse_NewtonSoftJson)]
318+
319+
In the sample app, comment out the `SYSTEM_TEXT_JSON` [preprocessor directive](xref:index#preprocessor-directives-in-sample-code) in *CustomWriterStartup.cs* to enable the `Newtonsoft.Json` version of `WriteResponse`.
320+
321+
The health checks API doesn't provide built-in support for complex JSON return formats because the format is specific to your choice of monitoring system. Customize the response in the preceding examples as needed. For more information on JSON serialization with `System.Text.Json`, see [How to serialize and deserialize JSON in .NET](/dotnet/standard/serialization/system-text-json-how-to).
332322

333323
## Database probe
334324

@@ -525,11 +515,11 @@ The sample app demonstrates a memory health check with a custom response writer.
525515

526516
Register health check services with <xref:Microsoft.Extensions.DependencyInjection.HealthCheckServiceCollectionExtensions.AddHealthChecks*> in `Startup.ConfigureServices`. Instead of enabling the health check by passing it to <xref:Microsoft.Extensions.DependencyInjection.HealthChecksBuilderAddCheckExtensions.AddCheck*>, the `MemoryHealthCheck` is registered as a service. All <xref:Microsoft.Extensions.Diagnostics.HealthChecks.IHealthCheck> registered services are available to the health check services and middleware. We recommend registering health check services as Singleton services.
527517

528-
In the sample app (*CustomWriterStartup.cs*):
518+
In *CustomWriterStartup.cs* of the sample app:
529519

530520
[!code-csharp[](health-checks/samples/3.x/HealthChecksSample/CustomWriterStartup.cs?name=snippet_ConfigureServices&highlight=4)]
531521

532-
A health check endpoint is created by calling `MapHealthChecks` in `Startup.Configure`. A `WriteResponse` delegate is provided to the `ResponseWriter` property to output a custom JSON response when the health check executes:
522+
A health check endpoint is created by calling `MapHealthChecks` in `Startup.Configure`. A `WriteResponse` delegate is provided to the <Microsoft.AspNetCore.Diagnostics.HealthChecks.HealthCheckOptions.ResponseWriter> property to output a custom JSON response when the health check executes:
533523

534524
```csharp
535525
app.UseEndpoints(endpoints =>
@@ -541,9 +531,7 @@ app.UseEndpoints(endpoints =>
541531
}
542532
```
543533

544-
The `WriteResponse` method formats the `CompositeHealthCheckResult` into a JSON object and yields JSON output for the health check response:
545-
546-
[!code-csharp[](health-checks/samples/3.x/HealthChecksSample/CustomWriterStartup.cs?name=snippet_WriteResponse)]
534+
The `WriteResponse` delegate formats the `CompositeHealthCheckResult` into a JSON object and yields JSON output for the health check response. For more information, see the [Customize output](#customize-output) section.
547535

548536
To run the metric-based probe with custom response writer output using the sample app, execute the following command from the project's folder in a command shell:
549537

aspnetcore/host-and-deploy/health-checks/samples/2.x/HealthChecksSample/CustomWriterStartup.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ await context.Response.WriteAsync(
4848
private static Task WriteResponse(HttpContext httpContext,
4949
HealthReport result)
5050
{
51-
httpContext.Response.ContentType = "application/json";
51+
httpContext.Response.ContentType = "application/json; charset=utf-8";
5252

5353
var json = new JObject(
5454
new JProperty("status", result.Status.ToString()),

aspnetcore/host-and-deploy/health-checks/samples/3.x/HealthChecksSample/BasicStartup.cs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
using Microsoft.AspNetCore.Builder;
2-
using Microsoft.AspNetCore.Hosting;
32
using Microsoft.AspNetCore.Http;
43
using Microsoft.Extensions.DependencyInjection;
54

aspnetcore/host-and-deploy/health-checks/samples/3.x/HealthChecksSample/CustomWriterStartup.cs

Lines changed: 62 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,22 @@
1-
using System.Linq;
1+
#define SYSTEM_TEXT_JSON
2+
3+
using System;
4+
using System.IO;
5+
using System.Linq;
6+
#if SYSTEM_TEXT_JSON
7+
using System.Text;
8+
using System.Text.Json;
9+
#endif
210
using System.Threading.Tasks;
311
using Microsoft.AspNetCore.Builder;
412
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
5-
using Microsoft.AspNetCore.Hosting;
613
using Microsoft.AspNetCore.Http;
714
using Microsoft.Extensions.DependencyInjection;
815
using Microsoft.Extensions.Diagnostics.HealthChecks;
16+
#if !SYSTEM_TEXT_JSON
917
using Newtonsoft.Json;
1018
using Newtonsoft.Json.Linq;
19+
#endif
1120

1221
namespace SampleApp
1322
{
@@ -49,11 +58,55 @@ await context.Response.WriteAsync(
4958
});
5059
}
5160

52-
#region snippet_WriteResponse
53-
private static Task WriteResponse(HttpContext httpContext,
54-
HealthReport result)
61+
#if SYSTEM_TEXT_JSON
62+
#region snippet_WriteResponse_SystemTextJson
63+
private static Task WriteResponse(HttpContext context, HealthReport result)
64+
{
65+
context.Response.ContentType = "application/json; charset=utf-8";
66+
67+
var options = new JsonWriterOptions
68+
{
69+
Indented = true
70+
};
71+
72+
using (var stream = new MemoryStream())
73+
{
74+
using (var writer = new Utf8JsonWriter(stream, options))
75+
{
76+
writer.WriteStartObject();
77+
writer.WriteString("status", result.Status.ToString());
78+
writer.WriteStartObject("results");
79+
foreach (var entry in result.Entries)
80+
{
81+
writer.WriteStartObject(entry.Key);
82+
writer.WriteString("status", entry.Value.Status.ToString());
83+
writer.WriteString("description", entry.Value.Description);
84+
writer.WriteStartObject("data");
85+
foreach (var item in entry.Value.Data)
86+
{
87+
writer.WritePropertyName(item.Key);
88+
JsonSerializer.Serialize(
89+
writer, item.Value, item.Value?.GetType() ??
90+
typeof(object));
91+
}
92+
writer.WriteEndObject();
93+
writer.WriteEndObject();
94+
}
95+
writer.WriteEndObject();
96+
writer.WriteEndObject();
97+
}
98+
99+
var json = Encoding.UTF8.GetString(stream.ToArray());
100+
101+
return context.Response.WriteAsync(json);
102+
}
103+
}
104+
#endregion
105+
#else
106+
#region snippet_WriteResponse_NewtonSoftJson
107+
private static Task WriteResponse(HttpContext context, HealthReport result)
55108
{
56-
httpContext.Response.ContentType = "application/json";
109+
context.Response.ContentType = "application/json";
57110

58111
var json = new JObject(
59112
new JProperty("status", result.Status.ToString()),
@@ -63,9 +116,11 @@ private static Task WriteResponse(HttpContext httpContext,
63116
new JProperty("description", pair.Value.Description),
64117
new JProperty("data", new JObject(pair.Value.Data.Select(
65118
p => new JProperty(p.Key, p.Value))))))))));
66-
return httpContext.Response.WriteAsync(
119+
120+
return context.Response.WriteAsync(
67121
json.ToString(Formatting.Indented));
68122
}
69123
#endregion
124+
#endif
70125
}
71126
}

aspnetcore/host-and-deploy/health-checks/samples/3.x/HealthChecksSample/DBHealthStartup.cs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
using Microsoft.AspNetCore.Builder;
2-
using Microsoft.AspNetCore.Hosting;
32
using Microsoft.AspNetCore.Http;
43
using Microsoft.Extensions.Configuration;
54
using Microsoft.Extensions.DependencyInjection;

aspnetcore/host-and-deploy/health-checks/samples/3.x/HealthChecksSample/DbContextHealthStartup.cs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
using System;
22
using Microsoft.AspNetCore.Builder;
3-
using Microsoft.AspNetCore.Hosting;
43
using Microsoft.AspNetCore.Http;
54
using Microsoft.EntityFrameworkCore;
65
using Microsoft.Extensions.Configuration;

aspnetcore/host-and-deploy/health-checks/samples/3.x/HealthChecksSample/LivenessProbeStartup.cs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,7 @@
33
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
44
using Microsoft.AspNetCore.Http;
55
using Microsoft.Extensions.DependencyInjection;
6-
using Microsoft.Extensions.DependencyInjection.Extensions;
76
using Microsoft.Extensions.Diagnostics.HealthChecks;
8-
using Microsoft.Extensions.Hosting;
97
using SampleApp.Services;
108

119
namespace SampleApp

aspnetcore/host-and-deploy/health-checks/samples/3.x/HealthChecksSample/ManagementPortStartup.cs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
using Microsoft.AspNetCore.Builder;
2-
using Microsoft.AspNetCore.Hosting;
32
using Microsoft.AspNetCore.Http;
43
using Microsoft.Extensions.Configuration;
54
using Microsoft.Extensions.DependencyInjection;
Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,14 @@
11
<Project Sdk="Microsoft.NET.Sdk.Web">
22

33
<PropertyGroup>
4-
<TargetFramework>netcoreapp3.0</TargetFramework>
4+
<TargetFramework>netcoreapp3.1</TargetFramework>
55
</PropertyGroup>
66

77
<ItemGroup>
8-
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0" />
9-
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="3.0.0" />
10-
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
11-
<PackageReference Include="System.Data.SqlClient" Version="4.7.0" />
12-
<PackageReference Include="AspNetCore.HealthChecks.SqlServer" Version="2.2.1" />
8+
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.0" />
9+
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="3.1.0" />
10+
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
11+
<PackageReference Include="AspNetCore.HealthChecks.SqlServer" Version="3.0.0" />
1312
</ItemGroup>
1413

1514
</Project>

0 commit comments

Comments
 (0)