【发布时间】:2026-02-01 23:50:01
【问题描述】:
我已将大量路由映射到我的 MVC4 项目,如下所示:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// API routing
routes.MapHttpRoute(
name: "SomeApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Default controller mapping for non-web api views (testing)
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
//etc.
}
这按计划进行,并且我的路线已正确注册。但是,稍后在我的视图中,我只想显示某些路线的 api,并允许用户选择显示 api 的路线。为此,我需要能够遍历我添加的路由并使用它们的字符串值来过滤出我想要使用的路由(下面的示例显示了我如何设置一个列表以仅使用 @987654323 显示 api 方法@路线)。
var list = group.Where(g => (g.Route.RouteTemplate == "api/{controller}/{id}"));
我不确定该怎么做。我偶然发现了this tidbit,但是RouteTable.Routes 中的数据不能通过Route 类型进行迭代,而只能通过RouteBase 类型进行迭代(即使Route 扩展了这个类),它没有方法可以我可以看到检索路由字符串,RouteTemplate。
所以,看起来我的主要难题是弄清楚如何遍历 RouteTable.Routes 并存储我映射的 HttpRoutes。任何帮助/想法将不胜感激!
【问题讨论】:
-
您能否详细说明此声明?
I am wanting to only display the api for certain routes, as well as allow the user to select which routes to display the api for。如果您只想通过 Web API 路由集合进行迭代,您可以执行类似GlobalConfiguration.Configuration.Routes的操作来获取HttpRouteCollection。该集合将包含您所有的 api 路由。 -
KiranChalla:这正是我想要的!感谢您的快速修复。供其他人用作参考,这是可用于迭代(并在 Razor 中显示)注册的 API 路由的代码:
@{var routes = GlobalConfiguration.Configuration.Routes;} @foreach (var r in routes) { @r.RouteTemplate<br /> } -
酷..让我用这个添加一个答案。
-
听起来不错。如果您愿意,可以将我的示例代码合并到其中。我上面评论中的格式看起来很糟糕。
标签: asp.net asp.net-mvc-4 asp.net-web-api asp.net-mvc-routing