.NET Core 3.x 中的多个运行状况检查端点

h-r*_*rai 4 .net asp.net-mvc .net-core asp.net-core

有没有办法在 .NET Core 3.x 中配置多个健康检查端点?

app.UseEndpoints(endpoints =>
{
    endpoints.MapHealthChecks("/health");
};
Run Code Online (Sandbox Code Playgroud)

这就是我目前所拥有的,我似乎无法在此之上配置另一个。

在这种情况下重定向将不起作用,因为其中一个端点将位于防火墙后面。

itm*_*nus 9

由于HealthChecks它是一个普通的中间件,因此您始终可以像其他普通中间件一样配置管道。

例如:

//in a sequence way
app.UseHealthChecks("/path1");
app.UseHealthChecks("/path2");

// in a branch way: check a predicate function dynamically
app.MapWhen(
    ctx => ctx.Request.Path.StartsWithSegments("/path3") || ctx.Request.Path.StartsWithSegments("/path4"), 
    appBuilder=>{
        appBuilder.UseMiddleware<HealthCheckMiddleware>();
    }
);

// use endpoint routing
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    endpoints.MapHealthChecks("/health1");
    endpoints.MapHealthChecks("/health2");
});

Run Code Online (Sandbox Code Playgroud)


小智 6

不确定您拥有多个健康检查端点的目的是什么。

如果是支持不同的“活性”和“就绪”健康检查,那么微软文档“过滤健康检查”指出了正确的方法。

本质上,它依赖于向您的健康检查添加标签,然后使用这些标签路由到适当的控制器。您无需使用“实时”标签指定健康检查,因为您可以立即使用基本的 Http 测试。

在 Startup.ConfigureServices()

services.AddHealthChecks()
        .AddCheck("SQLReady", () => HealthCheckResult.Degraded("SQL is degraded!"), tags: new[] { "ready" })
        .AddCheck("CacheReady", () => HealthCheckResult.Healthy("Cache is healthy!"), tags: new[] { "ready" });
Run Code Online (Sandbox Code Playgroud)

在 Startup.Configure()

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

    endpoints.MapHealthChecks("/health/live", new HealthCheckOptions()
    {
        Predicate = (_) => false});
});
Run Code Online (Sandbox Code Playgroud)