2011-02-14 61 views
1

编辑:对不起,我解释得很糟糕。基本上,在下面的例子中,我希望“this-is-handling-by-content-controller”是“id”,所以我可以在ContentController中将其作为操作参数来抓取它,但我想通过根的网站,例如mysite.com/this-is-not-passed-to-homecontroller。C#MVC 3根路由似乎没有工作

我想创建一个根路由,将去一个单独的控制器(而不是家)。

我跟着“RootController”示例发布在其他地方,实现IRouteConstraint,但它似乎不工作,我已经浪费了几个小时在这!

基本上,我有一个LoginController,一个HomeController和一个ContentController。

我希望能够通过去http://mysite/查看HomeController/Index。我希望能够通过去http://mysite/Login查看LoginController/Index。但是..我想要ContentController /索引被调用,如果任何其他结果发生,例如:http:/ mysite/this-is-by-content-controller

有没有一种优雅的方式来做到这一点?

这是我最后一次尝试。我已经剪切/粘贴/复制/划伤我的头这么多次的有点乱:

routes.MapRoute(
      "ContentPages", 
      "{action}", 
      new { Area = "", controller = "ContentPages", action = "View", id = UrlParameter.Optional }, 
      new RootActionConstraint() 
      ); 

     routes.MapRoute(
      "Default", // Route name 
      "{controller}/{action}/{id}", // URL with parameters 
      new { Area = "", controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults 
      new string[] { "Website.Controllers" } 
     ); 

任何帮助,不胜感激!

化学

+0

这可能会涵盖你在找什么。处理不匹配的路线并不是真正的路线引擎工作。 http://stackoverflow.com/questions/317005/default-route-for-all-extreme-situations/317023#317023 – Brettski 2011-02-14 03:35:44

回答

0

假设你有ContentController.Index(string id)处理路线相匹配的约束,这应该工作:

routes.MapRoute(
     "ContentPages", 
     "{id}", 
     new { Area = "", controller = "Content", action = "Index" }, 
     new { id = new RootActionConstraint() } 
     ); 

routes.MapRoute(
     "Default", // Route name 
     "{controller}/{action}/{id}", 
     new { Area = "", controller = "Home", action = "Index", id = UrlParameter.Optional }, 
     new string[] { "Website.Controllers" } 
    ); 
+0

什么是RootActionConstraint?我有好奇心搜索它,并冒着出现_无法搜索_我没有找到任何东西。这个约束可以定制吗? – 2011-06-04 10:50:29

+0

是的,OP提到`RootActionConstraint`是'IRouteConstraint`的自定义实现。 – dahlbyk 2011-06-05 03:10:47

1

我会做一些类似的,但如果你记住这可能不是最好的解决办法未来增加更多的控制器。

routes.MapRoute(
    "HomePage", 
    "", 
    new { controller = "Home", action = "Index", id="" } 
); 
routes.MapRoute(
    "Home", 
    "home/{action}/{id}", 
    new { controller = "Home", action = "Index", id="" } 
); 
routes.MapRoute(
    "Login", 
    "Login/{action}/{id}", 
    new { controller = "Login", action = "Index", id="" } 
); 
//... if you have other controller, specify the name here 

routes.MapRoute(
    "Content", 
    "{*id}", 
    new { controller = "Content", action = "Index", id="" } 
); 

第一条路线是为您的youwebsite.com/调用您的Home-> Index。第二条路线是在您的主控制器上执行其他操作(yourwebsite.com/home/ACTION)。

第三个用于您的LoginController(yourwebsite.com/login/ACTION)。

最后一个是你的内容 - >索引(yourwebsite.com/anything-that-goes-here)。

public ActionResult Index(string id) 
{ 
    // id is "anything-that-goes-here 
}