ASP.NET EF核心运行状况检查仅返回200状态

时间:2020-04-23 05:24:08

标签: c# asp.net-core entity-framework-core health-check

我目前正在使用PostgreSQL和Docker容器下的EntifyFramework Core在Identity ASP.NET Core 3.1项目上实施运行状况检查。

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

  • Microsoft.EntityFrameworkCore 3.1.3
  • Npgsql.EntityFrameworkCore.PostgreSQL 3.1.3
  • Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore 3.1.3
  • Microsoft.AspNetCore.Identity.EntityFrameworkCore 3.1.3

这是我的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终结点,直到我有意在docker中停止PostgreSQL容器,我都收到了200状态代码的健康响应。

我希望从/ health收到503状态代码,且响应不健康,但是空白响应却返回200状态代码

这是邮递员结果的快照 enter image description here

1 个答案:

答案 0 :(得分:0)

我认为当您请求 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") 
            });
    });   
}

您可以阅读健康检查here