在http://ASP.NET Core中实现健康检查
要实现运行状况检查,您需要在项目中安装 Microsoft.AspNetCore.Diagnostics.HealthChecks
。
接下来,在ConfigureServices
方法中添加运行状况检查中间件。
public void ConfigureServices(IServiceCollection services)
{
services.AddHealthChecks();
services.AddControllers();
}
然后修改Configure
方法,使用中间件:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHealthChecks("/health");
});
}
现在,准备工作完成,运行程序然后访问 /health, 您将看到下边结果:

HealthCheckService
.NET Core提供了一个HealthCheckService类,我们可以把健康检查的放到我们的控制器中,就像这样:
public class HealthController : ControllerBase
{
private readonly ILogger<HealthController> _logger;
private readonly HealthCheckService _healthCheckService;
public HealthController(ILogger<HealthController> logger,
HealthCheckService healthCheckService)
{
_healthCheckService = healthCheckService;
_logger = logger;
}
[HttpGet]
public async Task<IActionResult> Get()
{
var report = await _healthCheckService.CheckHealthAsync();
return report.Status == HealthStatus.Healthy ? Ok(report) :
StatusCode((int)HttpStatusCode.ServiceUnavailable, report);
}
}
现在,如果您尝试访问/health,您将看到相同的结果。
接下来,我们将实现数据库运行状态检查:
EntityFramework Core 健康检查
首先,还是需要安装Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore
到我们的项目中。
接下来,我们拿到数据库上下文,然后修改代码:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddApiVersioning();
}
然后,运行程序,现在访问 /health 返回的结果是这样:

IHealthCheck
一些情况下,默认的健康检查可能不满足我们的需求,那么可以继承 IHealthCheck 接口,自定义我们的健康检查的逻辑。
public class ApiHealthCheck : IHealthCheck
{
private readonly IHttpClientFactory _httpClientFactory;
public ApiHealthCheck(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context,
CancellationToken cancellationToken = default)
{
using (var httpClient = _httpClientFactory.CreateClient())
{
var response = await httpClient.GetAsync("https://your-api-service.endpoint");
if (response.IsSuccessStatusCode)
{
return HealthCheckResult.Healthy($"API is running.");
}
return HealthCheckResult.Unhealthy("API is not running");
}
}
}
然后修改代码如下:
public void ConfigureServices(IServiceCollection services)
{
services.AddHealthChecks()
.AddDbContextCheck<WeatherForecastDbContext>()
.AddCheck<ApiHealthCheck>("ApiHealth");
services.AddControllers();
}
然后,运行程序,访问 /health,结果如下:

原文作者: Anuraj
原文链接: https://dotnetthoughts.net/implementing-health-check-aspnetcore/
最后
欢迎扫码关注我们的公众号 【全球技术精选】,专注国外优秀博客的翻译和开源项目分享,也可以添加QQ群 897216102

转 https://zhuanlan.zhihu.com/p/346710313
标签:
.net core
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)