2015-02-24 80 views
0

这是我设计RegisterRoutes函数的方式。并根据条件选择动作为HomeController。到现在为止还挺好。在路由中动态更改默认操作 - MVC

string env = "Index"; 
if (some condition from config) 
{ 
    env = "Test"; 
} 
routes.MapRoute(
    "Default",            
    "{controller}/{action}/{id}",       
    new { controller = "Home", action = env, id = "" } 
); 

问题就在这里开始的时候我在默认情况下,如果不指定一个动作(如:打电话SampleController)reirecting到另一个控制器如果包膜被设置为“ENV”(这是在的RegisterRoutes集称为。 “指数”指数动作被调用,如果包膜被设置为“测试”测试的行动被称为在所有其他控制器以及。

我的目的只是为了HomeController的这种情况下应设置以及所有其他控制器我想指数作为默认动作

我该如何做这项工作?可以动态更改所有其他控制器的操作?有没有更好的办法可以做到这一点。

分享您的建议

感谢

+1

你可以做一个具体的路线' “首页/ {行动}/{ID}”,新{控制器= “家”,行动= ENV}'和默认路由'“{控制器}/{action}/{id}“,新的{controller =”Home“,action =”Index“}' – 2015-02-24 09:38:13

+0

@StephenMuecke谢谢!我尝试过,但总是默认路由被调用? – Peru 2015-02-24 14:11:15

+0

您是否首先放置了“Home/{action}/{id}”? (顺序很重要) – 2015-02-25 00:04:15

回答

2

我不认为你应该在你的路由引擎做到这一点。我会用代码路由所有内容,并从那里调用正确的操作。例如:

public ActionResult Index() 
{ 
    switch(config) 
    { 
     case "OtherAction": 
      return OtherAction(); 

     case "AnotherAction": 
      return AnotherAction(); 

     case "Index": 
      break; 

     default: 
      //Er, how did we get here? 
      throw new HttpNotFoundException(); 
    } 

    //Normal index action continues here... 

} 

public ActionResult OtherAction() { ... } 
public ActionResult AnotherAction() { ... }