How do I programatically list all routes in .NET Core Web API project?

Viewed 1286

I have an ASP.NET Core 5 Web API where routes are not matched. It works fine locally, but it's not working on the server. The logs show me

No candidates found for the request path

but I see the request path and it is correct.

I would like to log all the routes, just to see what my application thinks are the routes. It may help to see what is different on the server.

2 Answers

Try the following:

  1. Add IActionDescriptorCollectionProvider (from Microsoft.AspNetCore.Mvc.Infrastructure) as a parameter to Configure(...) within Startup.cs.
  2. Iterate over ActionDescriptors of IActionDescriptorCollectionProvider.

Example

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILogger log, IActionDescriptorCollectionProvider actionProvider)
{
    // configuration

    app.UseMvc();

    var routes = actionProvider.ActionDescriptors.Items
        .Where(x => x.AttributeRouteInfo != null);

    foreach(var route in routes)
    {
        log.LogDebug($"{route.AttributeRouteInfo.Template}");
    }
}
Related