From 74d900ea56ff06ed7d1be9d5ac94af723c3ed1ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Luthi?= Date: Tue, 11 Dec 2018 10:57:29 +0100 Subject: [PATCH] Add setter to HealthCheckOptions.ResultStatusCodes All other properties (`Predicate`, `ResponseWriter` and `AllowCachingResponses`) have a setter but `ResultStatusCodes` doesn't. Without a setter, reusing the same status to http status code mapping is impossible and leads to duplicate code that looks like this: ```csharp private static void ConfigureHealthChecks(IApplicationBuilder app, HealthCheckServiceOptions options) { app.UseHealthChecks("/health", new HealthCheckOptions { ResultStatusCodes = { [HealthStatus.Healthy] = StatusCodes.Status200OK, [HealthStatus.Degraded] = StatusCodes.Status400BadRequest, [HealthStatus.Unhealthy] = StatusCodes.Status503ServiceUnavailable } }); foreach (var name in options.Registrations.Select(e => e.Name)) { app.UseHealthChecks($"/health/{name}", new HealthCheckOptions { Predicate = registration => registration.Name == name, ResultStatusCodes = { [HealthStatus.Healthy] = StatusCodes.Status200OK, [HealthStatus.Degraded] = StatusCodes.Status400BadRequest, [HealthStatus.Unhealthy] = StatusCodes.Status503ServiceUnavailable } }); } } ``` With a setter, this code could be rewritten in a *don't repeat yourself* (DRY) way: ```csharp private static void ConfigureHealthChecks(IApplicationBuilder app, HealthCheckServiceOptions options) { var resultStatusCodes = new Dictionary { [HealthStatus.Healthy] = StatusCodes.Status200OK, [HealthStatus.Degraded] = StatusCodes.Status400BadRequest, [HealthStatus.Unhealthy] = StatusCodes.Status503ServiceUnavailable }; app.UseHealthChecks("/health", new HealthCheckOptions { ResultStatusCodes = resultStatusCodes }); foreach (var name in options.Registrations.Select(e => e.Name)) { app.UseHealthChecks($"/health/{name}", new HealthCheckOptions { Predicate = registration => registration.Name == name, ResultStatusCodes = resultStatusCodes }); } } ``` --- src/Middleware/HealthChecks/src/HealthCheckOptions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Middleware/HealthChecks/src/HealthCheckOptions.cs b/src/Middleware/HealthChecks/src/HealthCheckOptions.cs index 16b81c2b96..d4e63cee97 100644 --- a/src/Middleware/HealthChecks/src/HealthCheckOptions.cs +++ b/src/Middleware/HealthChecks/src/HealthCheckOptions.cs @@ -28,7 +28,7 @@ namespace Microsoft.AspNetCore.Diagnostics.HealthChecks /// Gets a dictionary mapping the to an HTTP status code applied to the response. /// This property can be used to configure the status codes returned for each status. /// - public IDictionary ResultStatusCodes { get; } = new Dictionary() + public IDictionary ResultStatusCodes { get; set; } = new Dictionary() { { HealthStatus.Healthy, StatusCodes.Status200OK }, { HealthStatus.Degraded, StatusCodes.Status200OK },