ASP.NET 使用路由配置在多租户环境中进行核心健康检查

ASP.NET Core Health checks in multi tenant environment using routing configuration

我开始使用来自 Asp.net Core 的健康检查,我喜欢它们,但我找不到一种简单的方法将它与基于租户的路由连接起来,例如支持:

如果我用这种方法成功了,我可以使用标签来过滤要使用的健康检查,但不幸的是我没有为请求配置路由。

app.UseEndpointRouting();
app.UseHealthChecks("/{tenant}/health", new HealthCheckOptions
    {
        ResponseWriter = WriteCustomHealthResponse,
        AllowCachingResponses = false,
        Predicate = _ => _.Tags.Contains("tenant-specific")
    });

以上代码没有正确路由。 我探索了使用如下内容的可能性:

app.MapWhen(context => 
    context.Request.Method == HttpMethod.Get.Method &&
    context.Request.?ROUTEDATA?.SOMECHECK("/{tenant}/HealthCheck"),
                builder => builder.UseHealthChecks());

但在这种情况下,我没有办法检查路由是否正确。

到目前为止,我找到的解决方案是使用查询字符串参数并使用 IHttpContextAccessor 搜索租户参数。 为此,我创建了 IHealthCheck.

的基本抽象实现
public abstract class BaseTenantHealthCheck : IHealthCheck
{
    private IHttpContextAccessor _httpContextAccessor;

    public BaseTenantHealthCheck(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    protected string GetTenant()
    {
        return _httpContextAccessor?.HttpContext?.Request?.Query["tenant"].ToString();
    }

    protected bool IsTenantSpecificCheck() => !string.IsNullOrEmpty(GetTenant());

    public abstract Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context,
        CancellationToken cancellationToken = default(CancellationToken));
}

在实现中 class 然后我传递如下所示的上下文访问器。

public class MylAvailabilityHealthCheck : BaseTenantHealthCheck
{
    public MyAvailabilityHealthCheck(IOptionsMonitor<MyAvailabilityCheckOptions> options, IHttpContextAccessor httpContextAccessor)
    : base(httpContextAccessor)
    {
        [..]

要访问我使用的健康检查:

  • http://{url}/health [用于多租户检查]
  • http://{url}/health?tenant=TenantName [针对特定租户的检查]

我期待听到是否有更优雅的方法来做到这一点。