ASP.NET core 使用 Health Check UI

Evan
evan.fang
Published in
6 min readFeb 22, 2021

在系統上線後,經常會有health check的需求,如:檢查資料庫連線是否正常、雲端服務是否正常。本文將模擬一個檢查外部依賴的第三方API是否正常運作,並提供health check api以及一個health check的使用者介面。

參考:

本文範例程式碼: Github

套件版本:

  • dotnet core: 3.1.405
  • AspNetCore.HealthChecks.UI: 3.1.3
  • AspNetCore.HealthChecks.UI.Client: 3.1.2
  • AspNetCore.HealthChecks.UI.InMemory.Storage: 3.1.2
  • AspNetCore.HealthChecks.Uris: 3.1.2

開發環境:

  • MAC + Vscode

先新增一個.net core的web專案(參考這裏):

dotnet new webapp -o aspnetcoreappcd aspnetcoreappdotnet dev-certs https --trust

新增相依套件:

dotnet add package AspNetCore.HealthChecks.UI --version 3.1.3dotnet add package AspNetCore.HealthChecks.UI.Client --version 3.1.2dotnet add package AspNetCore.HealthChecks.UI.InMemory.Storage --version 3.1.2dotnet add package AspNetCore.HealthChecks.Uris --version 3.1.2

結果如下:

aspnetcoreapp.csproj

調整Startup.cs的程式碼。

在ConfigureServices方法中,啟用health check ui,並指定ui使用的儲存方式為memory:

services  .AddHealthChecksUI()  .AddInMemoryStorage();

在ConfigureServices方法中,啟用health check,並指定要對依賴的第三方API進行health check:

services  .AddHealthChecks()  .AddUrlGroup(new Uri("https://www.google.com"), "Third party api health check", HealthStatus.Degraded);

結果如下:

Startup.cs

調整Configure方法,增加health check相關的route。

增加/health,可以以API的方式回傳health check的狀態。增加以下程式碼到Configure方法中:

app.UseHealthChecks("/health", new HealthCheckOptions(){  ResponseWriter = async (context, report) =>  {    var result = JsonConvert.SerializeObject(      new      {        status = report.Status.ToString(),        errors = report.Entries.Select(e => new { key = e.Key, value = Enum.GetName(typeof(HealthStatus), e.Value.Status) })      });  context.Response.ContentType = MediaTypeNames.Application.Json;  await context.Response.WriteAsync(result);  }});

增加/hc,指定寫出health check結果的方式為ui:

app.UseHealthChecks("/hc", new HealthCheckOptions(){  Predicate = _ => true,  ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse});

增加/hc-ui,指定health check ui:

app.UseHealthChecksUI(options =>{  options.UIPath = "/hc-ui";});

結果如下:

Startup.cs

調整appsettings.json,增加health check ui要使用的設定:

"HealthChecks-UI": {  "HealthChecks": [    {      "Name": "Health Check Demo",      "Uri": "http://localhost:5000/hc"    }  ],  "EvaluationTimeOnSeconds": 10,  "MinimumSecondsBetweenFailureNotifications": 60}

結果如下:

appsettings.json

啟動專案:

dotnet run

執行結果:

/health

/health

/hc

/hc

/hc-ui

/hc-ui

展開可以看detail:

觀察log,發現正定期在做health check:

--

--