ASP.NET MVC语言更改链接

时间:2011-06-27 14:57:09

标签: asp.net-mvc-3 internationalization

我有一个ASP.NET MVC站点,它使用Resources两种语言。要允许服务器以适当的语言显示网站(取决于用户浏览器中配置的网站),我将以下内容放在我的web.config中:

<globalization culture="es-es" uiCulture="auto" />

如何添加链接以更改uiCulture?我想将选择存储在cookie中,如果它不存在,那么请回到浏览器配置......是否可能?

4 个答案:

答案 0 :(得分:30)

您可以查看following guide。它使用Session来存储当前用户语言首选项,但可以非常容易地调整代码以使用cookie。这个想法是你将有一个控制器动作:

public ActionResult ChangeCulture(string lang, string returnUrl)
{
    var langCookie = new HttpCookie("lang", lang)
    {
        HttpOnly = true
    };
    Response.AppendCookie(langCookie);
    return Redirect(returnUrl);
}

然后在Global.asax中您可以订阅Application_AcquireRequestState事件,以便根据Cookie的值设置当前的线程文化:

protected void Application_AcquireRequestState(object sender, EventArgs e)
{
    var langCookie = HttpContext.Current.Request.Cookies["lang"];
    if (langCookie != null)
    {
        var ci = new CultureInfo(langCookie.Value);
        //Checking first if there is no value in session 
        //and set default language 
        //this can happen for first user's request
        if (ci == null)
        {
            //Sets default culture to english invariant
            string langName = "en";

            //Try to get values from Accept lang HTTP header
            if (HttpContext.Current.Request.UserLanguages != null && HttpContext.Current.Request.UserLanguages.Length != 0)
            {
                //Gets accepted list 
                langName = HttpContext.Current.Request.UserLanguages[0].Substring(0, 2);
            }

            langCookie = new HttpCookie("lang", langName)
            {
                HttpOnly = true
            };


            HttpContext.Current.Response.AppendCookie(langCookie);
        }

        //Finally setting culture for each request
        Thread.CurrentThread.CurrentUICulture = ci;
        Thread.CurrentThread.CurrentCulture = ci;

        //The line below creates issue when using default culture values for other
        //cultures for ex: NumericSepratore.
        //Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);
    }
}

现在有人说使用cookies和会话存储当前语言不是SEO友好。当我需要本地化应用程序时,我更喜欢做的是使用包含语言的特殊路由:

routes.MapRoute(
    "Default",
    "{lang}/{controller}/{action}/{id}",
    new 
    { 
        lang = "en-US",   
        controller = "Home", 
        action = "Index", 
        id = UrlParameter.Optional 
    }
);

然后使用该语言为我的所有网址添加前缀。这为不同语言提供了唯一的URL,以便机器人可以正确地索引所有内容。现在剩下的就是修改Application_AcquireRequestState方法,以便它使用网址的lang标记,并根据其值设置正确的Thread.CurrentThread.CurrentUICultureThread.CurrentThread.CurrentCulture

现在,当您想要更改语言时,您只需生成正确的链接:

@Html.ActionLink("Page index en français", "index", new { lang = "fr-FR" })

答案 1 :(得分:5)

另一种选择,我觉得它更灵活

 protected override void ExecuteCore()
    {
        if (RouteData.Values["lang"] != null && !string.IsNullOrWhiteSpace(RouteData.Values["lang"].ToString()))
        {
            SetCulture(RouteData.Values["lang"].ToString());
        }
        else
        {
            var cookie = HttpContext.Request.Cookies["myappculture"];
            if (cookie != null)
            { SetCulture(cookie.Value); }
            else
            { SetCulture(HttpContext.Request.UserLanguages[0]);}
        }
        base.ExecuteCore();
    }

public ActionResult ChangeCulture(string lang, string returnUrl)
    {

        SetCulture(lang);
        // Little house keeping
        Regex re = new Regex("^/\\w{2,3}(-\\w{2})?");
        returnUrl = re.Replace(returnUrl,"/" + lang.ToLower());
        return Redirect(returnUrl);
    }

private void SetCulture(string lang)
    {
        CultureInfo ci = new CultureInfo(lang);
        System.Threading.Thread.CurrentThread.CurrentUICulture = ci;
        System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);

        // Force a valid culture in the URL
        RouteData.Values["lang"] = lang;

        // save the location into cookie
        HttpCookie _cookie = new HttpCookie("myappculture", Thread.CurrentThread.CurrentUICulture.Name);
        _cookie.Expires = DateTime.Now.AddYears(1);
        HttpContext.Response.SetCookie(_cookie);
    }

在视图中

Multilingual setup in view

我将资源保存在不同的项目中,如下所示

Resources in a different project and Its usage

答案 2 :(得分:1)

如果您使用App_GloabalResources来存储您的resx语言文件,您只需添加一个下拉列表来更改当前线程的UI文化,这将自动选择要显示的正确resx语言文件。 / p>

答案 3 :(得分:1)

App_GloabalResources在MVC程序设计方面不是正确的资源。见http://buildingwebapps.blogspot.no/2012/05/right-way-to-use-resource-files-for.html

相关问题