2015-02-24 70 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() { ... }