You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 6如何在运行时可靠获取健康检查路由?

如何可靠获取ASP.NET Core 6中健康检查的端点路由?

要可靠筛选健康检查端点,核心思路是利用框架为健康检查端点附加的专属元数据类型,而非依赖易变的显示名或魔术字符串。

实现步骤:

  1. 注入IEnumerable<EndpointDataSource>到你的服务或组件中:
private readonly IEnumerable<EndpointDataSource> _endpointDataSources;

public YourService(IEnumerable<EndpointDataSource> endpointDataSources)
{
    _endpointDataSources = endpointDataSources;
}
  1. 通过元数据筛选健康检查端点:
    健康检查端点会被自动附加HealthCheckEndpointMetadata元数据(来自Microsoft.AspNetCore.Diagnostics.HealthChecks命名空间),直接通过这个类型判断即可:
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Routing;

// 获取所有健康检查端点的路由信息
var healthCheckRoutes = _endpointDataSources
    .SelectMany(source => source.Endpoints)
    .OfType<RouteEndpoint>() // 筛选路由端点
    .Where(endpoint => endpoint.Metadata.OfType<HealthCheckEndpointMetadata>().Any())
    .Select(endpoint => new 
    {
        Route = endpoint.RoutePattern.RawText, // 路由路径(如/healthz)
        EndpointName = endpoint.DisplayName
    });

为什么这个方案可靠?

  • HealthCheckEndpointMetadata是ASP.NET Core健康检查组件的公开标记类型,专门用于标识健康检查端点,框架版本更新时不会随意变更(属于稳定的API约定)。
  • 完全避开了对显示名(如"Heath checks")或硬编码路由路径的依赖,从根源上避免了版本迭代导致的失效问题。

如果需要进一步验证,还可以检查端点的请求委托是否指向健康检查的处理逻辑,但元数据筛选的方式已经足够高效和可靠。

内容的提问来源于stack exchange,提问作者lonix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 07:45:51