Keeping Track of ASP.NET Core Endpoint Routing

07/22/2020

Keeping Track of ASP.NET Core Endpoint Routing

Use this quick snippet to keep track of the routes that are declared in your ASP.NET Core app.

I don't remember the source for where I first heard about the AspNetCore.RouteAnalyzer package by kobake, but I had been faithfully using it since the halcyon days of...ASP.NET Core 2.2... to help troubleshoot routing issues in my web apps. But after moving into ASP.NET Core 3.1, it became downright impossible to use the package in my apps.

Sure enough, the first issue listed in the repo indicates that the package is now obsolete, and that users can now apply the code snippet in the posted issue to get around this. I found this to be partially true, as the code didn't support Razor Pages.

So here today is a plaintext routing table that will give you an alphabetical listing of your Razor pages as well as your other routes. One thing you'll notice, sadly, is that you won't get HTTP method verbiage for your Razor pages, so you may only find this to be of some comfort. If you know how to include this, however, please don't hesitate to let us know and we'll update the code snippet - or, post it somewhere and we'll link to your more glorious workaround!

Put this in your Startup.cs

app.UseRouting(); // make sure this is here first!
app.UseEndpoints(endpoints =>
{
    endpoints.MapRazorPages();
    endpoints.MapControllers();
    endpoints.MapGet("/routes", request =>
    {
        var sb = new StringBuilder();
        foreach (var source in endpoints.DataSources)
        {
            foreach (var a in source.Endpoints.OrderBy(x => x.DisplayName))
            {
                if (a.Metadata.First() is PageRouteMetadata)
                {
                    sb.AppendLine(
                        $"PageRoute {{{a.DisplayName}, Route: {(a.Metadata.First() as PageRouteMetadata)?.PageRoute}}}");
                    continue;
                }

                sb.AppendLine(
                    $"Route: {{{((HttpMethodMetadata) a.Metadata.First(m => m is HttpMethodMetadata)).HttpMethods.First()}: {(a as RouteEndpoint)?.RoutePattern.RawText}}}");
            }
        }
        return request.Response.WriteAsync(sb.ToString());
    });
});

Looking for help building or integrating your web application with cloud and enterprise resources? Contact us for a quote - not only is it free, but we can help you find what you're looking for at a better price than most consulting firms!