2011-09-28 56 views
0

在我的MVC2應用程序中,我有一個AccountController類繼承自Controller。我想實現以下功能:當用戶試圖打開Account/Payments/NewPaymentAccountController.ExecuteNewPayment()方法應該被調用。如何將請求路由到MVC2中特定控制器中的特定操作?

我增加了以下路線:

routes.MapRoute(
    @"CreateNewRuntime", 
    @"{langId}/Account/Payments/NewPayment/{whatever}", 
    new { langId = @"default", controller = @"Account", action = @"ExecuteNewPayment"}); 

但是當我嘗試上面我與「請求URL」 /Account/Payments/NewPayment HTTP 404錯誤消息,當我這樣做在調試器下有一個例外

請求路徑

System.Web.Mvc.dll中發生類型'System.Web.HttpException'的第一次機會異常 附加信息:路徑'/ Account/Payments/NewPayment'的控制器未找到或未實現IController 。

我在做什麼錯?我如何執行映射?

回答

1

您需要包含langid作爲路由的一部分,否則即使您指定了默認值,MVC也不會將您的URI映射到它。

採取以下兩種途徑:

routes.MapRoute(
    @"CreateNewRuntime", 
    @"{langId}/Account/Payments/NewPayment/{whatever}", 
    new { langId = @"default", controller = @"Account", action = @"ExecuteNewPayment"}); 


routes.MapRoute(
    @"CreateNewRuntime1", 
    @"{langId}/{subLangId}/Account/Payments/NewPayment/{whatever}", 
    new { langId = @"default", subLangId= @"test", controller = @"Account", action = @"ExecuteNewPayment1"}); 

如果我指定的/Account/Payments/NewPayment的URI的途徑之一應該是選擇哪一個?如果MVC確實使用langId的默認值,那麼第一條路由將始終被使用,因爲它在另一條之前被聲明。如果你交換了兩個,那麼第二個總是會被調用。

當您在URI的開頭有不同的數據時,您需要指定它們,並且在指定路由時不能使用默認值。爲了讓這兩條路被打,你需要的/eng/Account/Payments/NewPayment一個URI和/eng/e/Account/Payments/NewPayment

+0

很傷心。所以我必須指定一條額外的路線,以便'/ language/Account/Payments/NewPayment'/Account/Payments/NewPayment'映射到相同的控制器 - 操作對還是有更好的方法? – sharptooth

+0

@sharptooth - 不幸的是,你需要一條適合這兩種風景的路線 – amurra

0

{language}沒有對應的默認值,是langid應該是language = @"default"

+0

我改變了這一點,但它根本沒有幫助。我也有許多其他路線有這樣的不匹配 - 他們確實有效。 – sharptooth

0

你需要的是一個自定義的路由處理 看一看this

問候。

2

我相信你應該使用這些航線,這裏在第一條路線,我不使用LANGID和

routes.MapRoute(
       @"CreateNewRuntime1", 
       @"Account/Payments/NewPayment/{whatever}", 
       new { langId="en-US",controller = @"Account", action = @"ExecuteNewPayment" }); 

     routes.MapRoute(
       @"CreateNewRuntime2", 
       @"{langId}/Account/Payments/NewPayment/{whatever}", 
      new { controller = @"Account", action = @"ExecuteNewPayment" }, 
      new { langId = "[a-z]{2}-[a-z]{2}" }); 

注將langId默認值設置爲「en-US」。在第二種路線langId是必要的,但是有一個正則表達式,以便您的頁面的其他路線不受干擾。沒有這個正則表達式,langid可以是其他任何東西。

相關問題