[英]C#, ASP.NET MVC / MVC2: Add wildcard route for specific controller - help building route
[英]How do I route a request to a specific action in a specific controller in MVC2?
在我的MVC2應用程序中,我有一個從Controller
繼承的AccountController
類。 我想實現以下目標:當用戶嘗試打開Account/Payments/NewPayment
應調用AccountController.ExecuteNewPayment()
方法。
我添加了以下路線:
routes.MapRoute(
@"CreateNewRuntime",
@"{langId}/Account/Payments/NewPayment/{whatever}",
new { langId = @"default", controller = @"Account", action = @"ExecuteNewPayment"});
但是當我嘗試請求上面的路徑時,我收到帶有“ Requested URL” /Account/Payments/NewPayment
HTTP 404錯誤消息,當我在調試器下執行此操作時,會出現異常
System.Web.Mvc.dll中發生類型為'System.Web.HttpException'的第一次機會異常。其他信息:找不到路徑'/ Account / Payments / NewPayment'的控制器或該控制器未實現IController。
我究竟做錯了什么? 如何執行映射?
我相信您應該使用這些路線,
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並將langId默認值設置為“ en-US”。 在第二個路由中,langId是必需的,但這里有一個正則表達式,以便不會干擾頁面的其他路由。 沒有此正則表達式,langid可以是其他任何東西。
您需要將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的開頭有不同的數據,則需要指定它們,並且在指定路由時不能使用默認值。 為了使這兩條路線都被擊中,您需要一個URI /eng/Account/Payments/NewPayment
和/eng/e/Account/Payments/NewPayment
{language}
沒有對應的默認值, langid
應該是language = @"default"
嗎?
您需要的是自定義路由處理程序,看看這個
問候。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.