如果您使用的是ASP.NET Core 3.0+,那么这意味着您正在使用终结点路由,然后您可以使用EndpointDataSource
列出所有路由。
将IEnumerable<EndpointDataSource>
注入到您的控制器/终结点,然后提取您需要的任何内容。它适用于控制器操作、终结点以及部分Razor页面(Razor页面似乎不会公开可用的HTTP方法)。
[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);
}
}
当您访问/-/info/endpoints
时,您将获得一个JSON格式的路由列表:
[
{
"method": "GET",
"route": "/-/info/endpoints",
"action": "Info.ListAllEndpoints",
"controllerMethod": "Playground.Controllers.InfoController:ListAllEndpoints"
},
{
"method": "GET",
"route": "/WeatherForecast",
"action": "WeatherForecast.Get",
"controllerMethod": "Playground.Controllers.WeatherForecastController:Get"
},
{
"method": "GET",
"route": "/hello",
"action": null,
"controllerMethod": null
},
{
"method": null,
"route": "/about",
"action": null,
"controllerMethod": null
},
]
public async Task<ActionResult> ListAllEndpoints()
改成了public IActionResult ListAllEndpoints()
。 - scilIEnumerable<EndpointDataSource>
而不只是EndpointDataSource
?DI容器(.Net 5/6)中只注册了一个EndpointDataSource
。 - GrangerIEnumerable<EndpointDataSource>
注入所有实现。请参见https://source.dot.net/#Microsoft.AspNetCore.Routing/EndpointDataSource.cs,e430965f5ce4b2ff,references - abdusco