2012-02-28 135 views
3

我創建與國際化的一個網站,我想要做的是支持URL這種格式:如何設置ASP.Net MVC路由參數

"{country}/{controller}/{action}" 

我怎麼能告訴路由引擎{國家}應該使用會話變量設置?

+0

詢問:如果您使用的是國家的路線,你爲什麼會需要會話中保持呢?您可以使用路線作爲通過頁面請求來堅持所選國家的手段,從而否定使用會話來記住這一點的必要性。 – 2012-02-28 17:17:31

+0

如果有人連接到本地主機/ {控制器} =「主頁」,{動作} =「索引」。但對於{country},如果用戶來自說英語的國家{country} =「en」,來自西班牙語國家「es」,來自法語國家「fr」等。我認爲將{country}存儲在會話變量中以重用它,但我願意接受所有建議。 – Swell 2012-02-28 17:33:11

回答

3

您可以使用自定義的Controller Factory來完成此操作。開始你的路線:

routes.MapRoute(
    "Default", // Route name 
    "{language}/{controller}/{action}/{id}", // URL with parameters 
    new { controller = "Home", action = "Index", language = "tr", id = UrlParameter.Optional }, // Parameter defaults 
    new { language = @"(tr)|(en)" } 
); 

我通過重寫的DefaultControllerFactoryGetControllerInstance方法處理文化。這個例子是如下:

public class LocalizedControllerFactory : DefaultControllerFactory { 

    protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType) { 

     //Get the {language} parameter in the RouteData 

     string UILanguage; 

     if (requestContext.RouteData.Values["language"] == null) { 

      UILanguage = "tr"; 
     else 
      UILanguage = requestContext.RouteData.Values["language"].ToString(); 

     //Get the culture info of the language code 
     CultureInfo culture = CultureInfo.CreateSpecificCulture(UILanguage); 
     Thread.CurrentThread.CurrentCulture = culture; 
     Thread.CurrentThread.CurrentUICulture = culture; 

     return base.GetControllerInstance(requestContext, controllerType); 
    } 

} 

你可以在這裏得到會議的價值,而不是硬編碼爲我做的。

並將其註冊在Global.asax中:

protected void Application_Start() { 

    //...  
    ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory()); 
} 
+0

這看起來不錯!謝謝! – Swell 2012-02-28 17:55:26