如何将除一个控制器以外的所有控制器都路由到“开始"操作,以及如何将所有其他控制器路由到“索引"?
我的主要起始页面是 ApplicantProfile
,所以我的默认路由如下:
My main starting page is ApplicantProfile
, so my default route looks like this:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "ApplicantProfile", action = "Start", id = UrlParameter.Optional }
);
此控制器没有公共访问的索引,但是其他所有索引都有.我想要的是通配符,例如
This controller has no index for public access, but all others do. What I would like is the wildcard equivalent, e.g.
routes.MapRoute(
name: "Others",
url: "{controller}/{action}/{id}",
defaults: new { controller = "*", action = "Start", id = UrlParameter.Optional }
);
我该如何实现?
这应该解决:
routes.MapRoute(
name: "Default",
url: "ApplicantProfile/{action}/{id}",
defaults: new { controller = "ApplicantProfile", action = "Start", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { action = "Index", id = UrlParameter.Optional }
);
假设您有ApplicantProfileController,HomeController和OtherController,则结果为:
Assuming you have ApplicantProfileController, HomeController and OtherController, this will result in:
- /ApplicantProfile→ApplicantProfileController.Start
- /其他→OtherController.Index
- /SomeOtherPath→默认的404错误页面
- /→默认的404错误页面
See http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/asp-net-mvc-routing-overview-cs for an introduction to routing. It's a bit old, but it covers the basics well.
路由自上而下进行,这意味着它在路由表中的第一个匹配项处停止.在第一种情况下,您将首先匹配您的ApplicantProfile路由,以便使用控制器.第二种情况从路径中获取Other,找到匹配的控制器并使用它.最后2个找不到匹配的控制器,并且没有指定默认值,因此返回默认404错误.我建议放置一个适当的错误处理程序.在此处和在此处查看答案.
Routing happens top-down, meaning it stops at the first match in the routing table. In the first case, you will match your ApplicantProfile route first, so that controller is used. The second case gets Other from the path, finds a matching controller and uses that. The last 2 do not find a matching controller and there is no default specified so a default 404 error is returned. I'd suggest putting in a proper handler for errors. See the answers here and here.