我是.NET Core的新手。我想要获取ASP.NET Core中所有已注册路由的列表。在ASP.NET MVC中,我们可以通过System.Web.Routing
中的路由表来实现,那么在ASP.NET Core中也有类似的东西吗?我想要在我的控制器操作中获取路由列表。
我是.NET Core的新手。我想要获取ASP.NET Core中所有已注册路由的列表。在ASP.NET MVC中,我们可以通过System.Web.Routing
中的路由表来实现,那么在ASP.NET Core中也有类似的东西吗?我想要在我的控制器操作中获取路由列表。
我创建了NuGet包"AspNetCore.RouteAnalyzer",提供了一个功能来获取所有路由信息。
如果您想尝试,请使用它。
PM> Install-Package AspNetCore.RouteAnalyzer
using AspNetCore.RouteAnalyzer; // Add
.....
public void ConfigureServices(IServiceCollection services)
{
....
services.AddRouteAnalyzer(); // Add
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
....
app.UseMvc(routes =>
{
routes.MapRouteAnalyzer("/routes"); // Add
....
});
}
运行项目后,您可以访问URL/routes
来查看您的项目的所有路由信息。
app.UseMvc
,有没有简单的方法来使用这个库? - workabyteIActionDescriptorCollectionProvider
中获取一个 ActionDescriptor
集合。在那里,你可以查看项目中引用的所有操作,并可以获取包含路由信息的 AttributeRouteInfo
或 RouteValues
。
示例:
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Infrastructure;
public class EnvironmentController : Controller
{
private readonly IActionDescriptorCollectionProvider _actionDescriptorCollectionProvider;
public EnvironmentController(IActionDescriptorCollectionProvider actionDescriptorCollectionProvider)
{
_actionDescriptorCollectionProvider = actionDescriptorCollectionProvider;
}
[HttpGet("routes", Name = "ApiEnvironmentGetAllRoutes")]
[Produces(typeof(ListResult<RouteModel>))]
public IActionResult GetAllRoutes()
{
var result = new ListResult<RouteModel>();
var routes = _actionDescriptorCollectionProvider.ActionDescriptors.Items.Where(
ad => ad.AttributeRouteInfo != null).Select(ad => new RouteModel
{
Name = ad.AttributeRouteInfo.Name,
Template = ad.AttributeRouteInfo.Template
}).ToList();
if (routes != null && routes.Any())
{
result.Items = routes;
result.Success = true;
}
return Ok(result);
}
}
internal class RouteModel
{
public string Name { get; set; }
public string Template { get; set; }
}
internal class ListResult<T>
{
public ListResult()
{
}
public List<RouteModel> Items { get; internal set; }
public bool Success { get; internal set; }
}
你还可以使用ActionDescriptors.Items
数组中的Template = x.AttributeRouteInfo.Template
值。以下是来自此处的完整代码示例:
[Route("monitor")]
public class MonitorController : Controller {
private readonly IActionDescriptorCollectionProvider _provider;
public MonitorController(IActionDescriptorCollectionProvider provider) {
_provider = provider;
}
[HttpGet("routes")]
public IActionResult GetRoutes() {
var routes = _provider.ActionDescriptors.Items.Select(x => new {
Action = x.RouteValues["Action"],
Controller = x.RouteValues["Controller"],
Name = x.AttributeRouteInfo.Name,
Template = x.AttributeRouteInfo.Template
}).ToList();
return Ok(routes);
}
}
ControllerActionDescriptor
来获得对控制器相关信息的键入访问。例如,如果你只对控制器的操作感兴趣,可以这样做:actionDescriptorCollectionProvider.ActionDescriptors.Items.OfType<ControllerActionDescriptor>()
(获取仅包含在控制器中定义的操作的列表,并且其中的项具有类型化属性,例如ControllerTypeInfo
)。 - undefinedusing System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ActionConstraints;
using Microsoft.AspNetCore.Mvc.Infrastructure;
[Route("")]
[ApiController]
public class RootController : ControllerBase
{
private readonly IActionDescriptorCollectionProvider _actionDescriptorCollectionProvider;
public RootController(IActionDescriptorCollectionProvider actionDescriptorCollectionProvider)
{
_actionDescriptorCollectionProvider = actionDescriptorCollectionProvider;
}
public RootResultModel Get()
{
var routes = _actionDescriptorCollectionProvider.ActionDescriptors.Items.Where(
ad => ad.AttributeRouteInfo != null).Select(ad => new RouteModel
{
Name = ad.AttributeRouteInfo.Template,
Method = ad.ActionConstraints?.OfType<HttpMethodActionConstraint>().FirstOrDefault()?.HttpMethods.First(),
}).ToList();
var res = new RootResultModel
{
Routes = routes
};
return res;
}
}
internal class RouteModel
{
public string Name { get; set; }
public string Template { get; set; }
public string Method { get; set; }
}
internal class RootResultModel
{
public List<RouteModel> Routes { get; set; }
}
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ActionConstraints;
using Microsoft.AspNetCore.Mvc.Infrastructure;
namespace My.WebApiProject.Controllers
{
public class EnvironmentController : Controller
{
private readonly IActionDescriptorCollectionProvider _actionDescriptorCollectionProvider;
public EnvironmentController(IActionDescriptorCollectionProvider actionDescriptorCollectionProvider)
{
_actionDescriptorCollectionProvider = actionDescriptorCollectionProvider;
}
[HttpGet("routes", Name = "ApiEnvironmentGetAllRoutes")]
public IActionResult GetAllRoutes()
{
/* intentional use of var/anonymous class since this method is purely informational */
var routes = _actionDescriptorCollectionProvider.ActionDescriptors.Items
.Where(ad => ad.AttributeRouteInfo != null)
.Select(x => new {
Action = null != x && null != x.RouteValues && null != x.RouteValues["action"] ? x.RouteValues["action"] : "n/a",
Controller = null != x && null != x.RouteValues && null != x.RouteValues["controller"] ? x.RouteValues["controller"] : "n/a",
Name = x.AttributeRouteInfo.Name ?? "n/a",
Template = x.AttributeRouteInfo.Template ?? "n/a",
Method = x.ActionConstraints?.OfType<HttpMethodActionConstraint>().FirstOrDefault()?.HttpMethods.First()
}).ToList();
return Ok(routes);
}
}
}
这里的 "n/a" 是指在某些情况下会出现。"Name = x.AttributeRouteInfo.Name ?? "n/a",
This below optional package may be required.
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.2.0" />
GetRouteData().Routers.OfType<RouteCollection>().First()
来访问RouteCollection
。app.UseRouter(r => {
r.MapGet("getroutes", async context => {
var routes = context.GetRouteData().Routers.OfType<RouteCollection>().First();
await context.Response.WriteAsync("Total number of routes: " + routes.Count.ToString() + Environment.NewLine);
for (int i = 0; i < routes.Count; i++)
{
await context.Response.WriteAsync(routes[i].ToString() + Environment.NewLine);
}
});
// ...
// other routes
});
请确保在路由处理程序内调用GetRouteData()
,否则它将返回null。
可以通过从 DI 中检索 EndpointDataSource 集合来列出路由的集合。
.NET 6 示例:
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();
欲了解更多详情,请点击此处
RouteValues
中获取信息。var routes = _actionDescriptorCollectionProvider.ActionDescriptors.Items
.Select(ad => new
{
Action = ad.RouteValues["action"],
Controller = ad.RouteValues["controller"]
}).Distinct().ToList();
RouteCollection
的路由器。要获取该类型的所有路由,您应该能够在RouteCollection
类型的路由器上调用.All()
。var routes = RouteData.Routers.OfType<RouteCollection>().All();
感谢:https://rimdev.io/get-registered-routes-from-an-asp.net-mvc-core-application/
如果.All()
无法正常工作,请参考上述文章。