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

 
 
  • Gérald Barré

When your ASP.NET Core application is big enough, you may want to have a comprehensive view of all routes. There are multiple ways to declare routes. You can use Minimal API, Controllers, Razor Pages, gRPC, Health checks, etc. But all of them use the same routing system under the hood.

The collection of routes can be listed by retrieving the collection of EndpointDataSource from DI.

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();

You can get more data about each endpoint if needed:

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?Buy Me A Coffee💖 Sponsor on GitHub