How to list all routes in an ASP.NET Core application

 
 
  • Gérald Barré

As your ASP.NET Core application grows, you may want a comprehensive view of all its routes. Routes can be declared in many ways: Minimal APIs, controllers, Razor Pages, gRPC, health checks, and more. All of them use the same routing system under the hood.

You can list all routes by retrieving the EndpointDataSource collection from the DI container.

Program.cs (C#)
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseRouting();

if (app.Environment.IsDevelopment())
{
    app.MapGet("/debug/routes", (IEnumerable<EndpointDataSource> endpointSources) =>
        string.Join("\n", endpointSources.SelectMany(source => source.Endpoints)));
}

app.Run();

To retrieve more details about each endpoint:

Program.cs (C#)
app.MapGet("/debug/routes", (IEnumerable<EndpointDataSource> endpointSources) =>
{
    var sb = new StringBuilder();
    var endpoints = endpointSources.SelectMany(es => es.Endpoints);
    foreach (var endpoint in endpoints)
    {
        if(endpoint is RouteEndpoint routeEndpoint)
        {
            _ = routeEndpoint.RoutePattern.RawText;
            _ = routeEndpoint.RoutePattern.PathSegments;
            _ = routeEndpoint.RoutePattern.Parameters;
            _ = routeEndpoint.RoutePattern.InboundPrecedence;
            _ = routeEndpoint.RoutePattern.OutboundPrecedence;
        }

        var routeNameMetadata = endpoint.Metadata.OfType<Microsoft.AspNetCore.Routing.RouteNameMetadata>().FirstOrDefault();
        _ = routeNameMetadata?.RouteName;

        var httpMethodsMetadata = endpoint.Metadata.OfType<HttpMethodMetadata>().FirstOrDefault();
        _ = httpMethodsMetadata?.HttpMethods; // [GET, POST, ...]

        // There are many more metadata types available...
});

#Additional resources

Routing in ASP.NET Core

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?