ASP.net MVC3多语言路由重写

Fio*_*onn 5 multilingual internationalization asp.net-mvc-routing asp.net-mvc-3

有没有什么好方法可以为多语言Web应用程序创建路由重写?


URL架构应如下所示

http://<Domainname>/{Language}/{Controller}/{Action}/{Id}

但是也应该支持没有语言部分的URL,但它们不应该直接映射到控制器,而是生成重定向响应.

这里重要的是,重定向不应该硬编码为特定语言,而是根据用户首选语言等因素确定.

注意:确定正确语言的过程不是问题,只是如何进行非静态重写.

谢谢

tug*_*erk 4

我通过以下路线做到了这一点;

    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)" }
        );
Run Code Online (Sandbox Code Playgroud)

我通过重写 DefaultControllerFactory 的 GetControllerInstance() 方法来处理区域性。示例如下;

public class NinjectControllerFactory : 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);
}

}
Run Code Online (Sandbox Code Playgroud)

并将其注册到global.asax;

protected void Application_Start() {

    //other things here


    ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
}
Run Code Online (Sandbox Code Playgroud)