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, int>
    {
        [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
        });
    }
}
```
This commit is contained in:
Cédric Luthi 2018-12-11 10:57:29 +01:00 committed by Ryan Nowak
parent 35d8ee6cdf
commit 74d900ea56
1 changed files with 1 additions and 1 deletions

View File

@ -28,7 +28,7 @@ namespace Microsoft.AspNetCore.Diagnostics.HealthChecks
/// Gets a dictionary mapping the <see cref="HealthStatus"/> to an HTTP status code applied to the response.
/// This property can be used to configure the status codes returned for each status.
/// </summary>
public IDictionary<HealthStatus, int> ResultStatusCodes { get; } = new Dictionary<HealthStatus, int>()
public IDictionary<HealthStatus, int> ResultStatusCodes { get; set; } = new Dictionary<HealthStatus, int>()
{
{ HealthStatus.Healthy, StatusCodes.Status200OK },
{ HealthStatus.Degraded, StatusCodes.Status200OK },