Home > database >  Determine health check routes at runtime in ASP.NET Core 6
Determine health check routes at runtime in ASP.NET Core 6

Time:07-20

I added health checks to my ASP.NET Core 6 app, and everything is working properly.

I need to determine (programmatically, at runtime) all the health check routes, e.g. /healthz, etc.

I tried:

// inject IEnumerable<EndpointDataSource>
// ...
var routes = _endpointDataSources.SelectMany(source => source.Endpoints);

But there's no way I can select the correct endpoints (using linq) without using a hack or magic string. The healthcheck endpoints have "Heath checks" as their display names, but I assume that can change at any time, so it's not reliable.

How can I get those endpoints in a reliable way that won't break on the next update?

CodePudding user response:

Health checks are (currently) implemented by creating a middleware pipeline and mapping the resulting delegate, with a display name "Health checks".

var pipeline = endpoints.CreateApplicationBuilder()
    .UseMiddleware<HealthCheckMiddleware>(args)
    .Build();

return endpoints.Map(pattern, pipeline)
    .WithDisplayName(DefaultDisplayName);

As you have discovered, you should be able to discover all endpoints, search for any health checks, and list their path via;

var sources = provider.GetService<IEnumerable<EndpointDataSource>>(); // via DI

var routes = sources
    .SelectMany(s => s.Endpoints)
    .OfType<RouteEndpoint>()
    .Where(e => e.DisplayName == "Health checks")
    .Select(e => e.RoutePattern)
    .ToList();

So to answer your actual question, while the method you would use to configure endpoint routes is unlikely to change. There are mentions in the documentation demonstrating how endpoint routing meta data can be examined. But I wouldn't expect any strong guarantee of future support.

  • Related