2013-02-01 65 views
1

我的主要起始页面是ApplicantProfile,所以我的默认路由看起来是这样的:如何将除了一个控制器以外的所有控制器路由到“开始”操作,并将所有其他控制器路由到“索引”?

routes.MapRoute(
    name: "Default", 
    url: "{controller}/{action}/{id}", 
    defaults: new { controller = "ApplicantProfile", action = "Start", id = UrlParameter.Optional } 
); 

该控制器具有公共接入没有指数,但所有其他人。我想要的是等效的通配符,例如

routes.MapRoute(
    name: "Others", 
    url: "{controller}/{action}/{id}", 
    defaults: new { controller = "*", action = "Start", id = UrlParameter.Optional } 
); 

我该如何做到这一点?

+0

是否有任何答案适合您?如果没有,你可以发布你如何解决它? –

+0

我其实没有机会尝试。我有更高的优先任务进行干预,但我很快就会回到这一点。 – ProfK

回答

4

这应该照顾它:

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,这将导致:

  • /ApplicantProfile → ApplicantProfileController.Start
  • /其他→ OtherController.Index
  • /SomeOtherPath →默认的404错误页面
  • /→默认的404错误页面

的介绍,参见路由http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/asp-net-mvc-routing-overview-cs。这有点旧,但它很好地涵盖了基础知识。

路由从上到下发生,意思是它停在路由表的第一个匹配处。在第一种情况下,您将首先匹配您的ApplicantProfile路线,以便使用控制器。第二种情况是从路径中获取其他,找到匹配的控制器并使用它。最后2个没有找到匹配的控制器,并且没有指定默认值,因此返回了默认的404错误。我建议在错误中加入适当的处理程序。请参阅答案herehere

+0

看起来很完美 –

+0

不,我没有任何这样的'OtherDefaultController'。我希望请求能够转到URL中包含的任何控制器。 – ProfK

+0

@ProfK我编辑了我的回复,希望能让事情更清楚。 –

1

这应该按您的要求

routes.MapRoute(
    name: "ApplicantProfile", 
    url: "ApplicantProfile/Start/{id}", 
    defaults: new { controller = "ApplicantProfile", action = "Start", id = UrlParameter.Optional } 
); 

routes.MapRoute(
    name: "Default", 
    url: "{controller}/{action}/{id}", 
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
); 

第一个是URL这将路线,你“开始”行动,另一种是默认的更换‘与您默认的

+0

这个解决方案的问题是,它会路由例如/ ApplicantProfile/Step2到'HomeController'。原来的问题对这一点并不明确,但如果我在真实项目中将这个问题作为要求给出,那我就是这样解释的。 –

1

的家’控制器默认应该转到配置文件控制器启动动作,所有其他请求应该着陆索引动作什么是控制器。

使用IRouteConstraint将约束添加到其他路由的URL,并将其放置在默认控制器上方与控制器的路由约束。

如果控制器不是ApplicationProfile使用它,您可以添加一个检查。

我希望这会有所帮助。

相关问题