2011-08-31 113 views
3

IAM具有控制器等,低于该另一控制器/动作是在路由表重定向到在路由未注册

public class InternalController : Controller 
{ 
/*this controller is not registered in routes table*/ 

     public ActionResult Foo() 
     { 
     return Content("Text from foo"); 
     } 
} 

未注册从我想调用哪个被登记在路由表另一控制器/前一个控制器的重定向动作,一个未在路由表中注册的动作。

public class AjaxController : Controller 
{ 
/*this controller is registered in routes table*/ 

     public ActionResult Foo() 
     { 

      /*FROM HERE HOW DO I RETURN CONTENTS OF 
      controller=InternalController, action = Foo 
      */ 

      /* 
       i tried below piece of code but that doesnt seem to work 
      */ 

      return RedirectToAction("Foo", "InternalController "); 
     } 
} 

定义的路由(只有一个项目加)

public void RegisterRoutes(RouteCollection routes) 
    { 
     routes.MapRoute("Ajax","ajax/{action}",new { 
     controller="Ajax", 
     action="Index" 
     }); 
    } 
+0

*未在路线中注册的控制器是什么* *?这对我来说没有任何意义。 –

+0

如果你的类是'InternalController',那么你应该通过'RedirectToAction(“Foo”,“Internal”)''重定向到“Internal”控制器(即不是“InternalController”)。 –

+0

@darin“未在路线中注册的控制器”:表示我没有在路线表中注册该控制器。 –

回答

0

现在你已经证明你的路由定义,很明显,你永远无法调用任何其它控制器比AjaxController。你只是禁止他们在你的路线,所以InternalController永远不能送达。你将不得不改变你的路线定义。

取决于你想要达到什么,以及如何你希望你的URL看起来像你有几个可能的原因:

  • 保留默认路由
  • 修改现有的路线定义,像这样:

    routes.MapRoute(
        "Ajax", 
        "{controller}/{action}", 
        new { controller = "Ajax", action = "Index" } 
    ); 
    
+0

这是否意味着它不可能(**,即使不使用重定向**)从'controller = AjaxControler,action = Foo'返回'controller = InternalController,action = Foo'的内容。 –

+0

@Rusi Nova,是的,这就是它的意思。不仅如此,AjaxControler无法实现,而且无处不在,甚至不需要在浏览器中输入一些url或其他内容,因为您的路由定义方式并不存在这样的url。您仍然可以保留默认路由(由新项目向导生成的路由)。 –

+0

是的,您需要访问的所有控制器(包括RedirectToAction调用)都需要在路由中注册 – BlackTigerX

1

如果您选择不注册的路线......那么你很可能在特定位置的文件/控制器会不变。

在这种情况下,只需使用“重定向”方法,而不是“RedirectToAction”。

例如:

return Redirect("~/Internal/Foo"); 
+0

当然没有路由它不会解决路径? – TheCodeKing

+0

我已经更新了这个问题。 –

0

您可以重定向多个URL和页面创建RedirectController:

public class RedirectController : Controller 
{ 
    public ActionResult Index() 
    { 
     var rd = this.RouteData.Values; 
     string controller = rd["controller2"] as string; 
     string action = rd["action2"] as string; 

     rd.Remove("controller2"); 
     rd.Remove("action2"); 
     rd.Remove("controller"); 
     rd.Remove("action"); 

     return RedirectToActionPermanent(action, controller, rd); 
    } 
} 

然后你就可以定义从旧的URL在路由表中重定向:

routes.MapRoute(
null, // Name 
"ajax/foo", 
new { controller = "Redirect", 
     action = "Index", 
     controller2 = "InternalController", 
     action2 = "Foo"} 
); 

这种模式也是有用的,如果您重定向旧网址到新的一个。例如:

routes.MapRoute(
null, // Name 
"default.aspx", // redirect from old ASP.NET 
new { controller = "Redirect", 
action = "Index", 
controller2 = "Home", 
action2 = "Index" } 
);