如何在 ASP.NET MVC 5 中设置指向同一控制器的 2 个路由
我有一个ASP.NET MVC 5网站,该网站具有控制器 myFirstController
。
这样,我可以使用 https://example.server.com/myfirst
加载索引视图。
另一方面,我还有另一种视图,该视图呈现链接(html a标签的href属性):
Url.Action("Index", "MyFirst")
该URL渲染会导致链接生成:
https://example.server.com/MyFirst
到目前为止,太好了。现在,我需要有一个类似的路由
https://example.server.com/MySecond
,即URL应该加载相同的 index
myFirst
控制器的视图,而无需创建名为 mySecondController
的新控制器。这就像拥有一个 myFirst
控制器别名名为 mysecond
。
在 ruteconfig.cs
文件中,我添加了以下内容:
routes.MapRoute(name: "MySecond",
url: "MySecond/{action}/{id}",
defaults: new { controller = "MyFirst", action = "Index", id = UrlParameter.Optional }
);
我对此代码遇到的问题是,我在其他视图中具有此渲染代码:
@if (somecondition)
{
... Url.Action("Index", "MyFirst") ...
}
else
{
... Url.Action("Index", "MySecond") ...
}
我需要,如果 somecondition
是正确的,渲染的URL为 https://example.server.com/myfirst
,如果是false,则渲染的URL为 https://example.server.server.server.com/mysecond 。
我遇到的问题是,两者都被渲染为 https://example.server.com/mysecond
。
我该如何完成这项任务?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
而不是使用
url.action
,使用url.route
,它允许解释传递申请渲染URL的路由的名称。要渲染
/mysecond
url,请传递mysecond
路由的名称。做同样的事情以渲染
/myFirst
url,但是由于它没有明确的路由名称,您必须同时传递默认路由的名称和的名称myfirst
控制器。您可以省略
index
操作的名称,因为已将其设置为默认一个。Instead of using
Url.Action
, useUrl.Route
as it allows to explictly pass the name of the route to apply for rendering the url.To render the
/MySecond
url, pass the name of theMySecond
route.Do the same to render the
/MyFirst
url, but since it doesn't have an explicit route name, you'll have to pass both the name of the default route and the name of theMyFirst
controller.You can omit the name of the
Index
action, as it has been set up as the default one.自定义路由应在默认路由前。
Custom route should be before default route.
在控制器中尝试使用
In the controller try using
而不是使用url.Action使用 url.route 。此方法可以选择提供路由名称,并可以选择操作和控制器。
您还可以在URLHELPER上创建扩展方法,以便您没有散落的“魔术字符串”的视图:
然后您可以使用
@url.myfirst()
或@url.mysecond ()
Instead of using Url.Action use Url.Route. This method has the option to provide the route name and optionally the action and controller.
You could also create extension methods on UrlHelper so that you don't have "magic strings" littered through out your views:
Then you can use
@Url.MyFirst()
or@Url.MySecond()
您可以将2个路由设置为相同的控制器,如下所示:
You can set 2 route point to the same controller like shown below: