如何将除一个控制器以外的所有控制器都路由到“开始"操作,以及如何将所有其他控制器路由到“索引"? [英] How do I route all but only one controller to the 'Start' action, and routes for all other controllers to 'Index'?

查看:59
本文介绍了如何将除一个控制器以外的所有控制器都路由到“开始"操作,以及如何将所有其他控制器路由到“索引"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的主要起始页面是 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.

这篇关于如何将除一个控制器以外的所有控制器都路由到“开始"操作,以及如何将所有其他控制器路由到“索引"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆