首页 > 解决方案 > ASP.NET EF Core 健康检查只返回 200 状态

问题描述

我目前正在使用 Docker 容器下的 PostgreSQL 和 EntifyFramework Core 对我的 Identity ASP.NET Core 3.1 项目进行健康检查。

这是我的项目中安装的 nuget 包

这是我的 Startup.cs 类

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<IdentityContext>(options => options.UseNpgsql(Configuration["Identity:ConnectionString"]));

    services.AddHealthChecks()
            .AddDbContextCheck<IdentityContext>("Database");

    services.AddControllers();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseHealthChecks("/health");
    app.UseHttpsRedirection();

    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
       endpoints.MapControllers();
    });   
}

一切正常,我通过访问 /health 端点获得了一个带有 200 状态代码的健康响应,直到我故意停止 Docker 中的 PostgreSQL 容器。

我期望从 /health 收到带有不健康响应的 503 状态代码,但收到带有 200 状态代码的空白响应

这是邮递员的结果快照 在此处输入图像描述

标签: c#asp.net-coreentity-framework-corehealth-check

解决方案


我认为当您请求 url “/health” 时未调用您的“数据库”检查。尝试使用标签注册 HealthCheck。然后用这个标签定义端点。

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<IdentityContext>(options => options.UseNpgsql(Configuration["Identity:ConnectionString"]));

    services.AddHealthChecks()
            .AddDbContextCheck<IdentityContext>("Database",tags: new[] { "live" });

    services.AddControllers();
}


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{       
    app.UseHttpsRedirection();

    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
       endpoints.MapControllers();

       endpoints.MapHealthChecks("/health/live", new HealthCheckOptions()
            {
                Predicate = (check) => check.Tags.Contains("live") 
            });
    });   
}

您可以在此处阅读有关健康检查的信息


推荐阅读