If you're on ASP.NET Core 3.0+, that means you're using endpoint routing, then you can list all routes with EndpointDataSource
s.
Inject IEnumerable<EndpointDataSource>
to your controller/endpoint then extract anything you need. It works with both controller actions, endpoints, and partially with razor pages (razor pages don't seem to expose available HTTP methods).
[Route("/-/{controller}")]
public class InfoController : Controller
{
private readonly IEnumerable<EndpointDataSource> _endpointSources;
public InfoController(
IEnumerable<EndpointDataSource> endpointSources
)
{
_endpointSources = endpointSources;
}
[HttpGet("endpoints")]
public async Task<ActionResult> ListAllEndpoints()
{
var endpoints = _endpointSources
.SelectMany(es => es.Endpoints)
.OfType<RouteEndpoint>();
var output = endpoints.Select(
e =>
{
var controller = e.Metadata
.OfType<ControllerActionDescriptor>()
.FirstOrDefault();
var action = controller != null
? $"{controller.ControllerName}.{controller.ActionName}"
: null;
var controllerMethod = controller != null
? $"{controller.ControllerTypeInfo.FullName}:{controller.MethodInfo.Name}"
: null;
return new
{
Method = e.Metadata.OfType<HttpMethodMetadata>().FirstOrDefault()?.HttpMethods?[0],
Route = $"/{e.RoutePattern.RawText.TrimStart('/')}",
Action = action,
ControllerMethod = controllerMethod
};
}
);
return Json(output);
}
}
when you visit /-/info/endpoints
, you'll get a list of routes as JSON:
[
{
"method": "GET",
"route": "/-/info/endpoints", // <-- controller action
"action": "Info.ListAllEndpoints",
"controllerMethod": "Playground.Controllers.InfoController:ListAllEndpoints"
},
{
"method": "GET",
"route": "/WeatherForecast", // <-- controller action
"action": "WeatherForecast.Get",
"controllerMethod": "Playground.Controllers.WeatherForecastController:Get"
},
{
"method": "GET",
"route": "/hello", // <-- endpoint route
"action": null,
"controllerMethod": null
},
{
"method": null,
"route": "/about", // <-- razor page
"action": null,
"controllerMethod": null
},
]