动态更改页面文化取决于区域

时间:2016-03-28 13:12:21

标签: c# asp.net asp.net-mvc culture

我需要根据Region在运行时更改文化。 我在web.config中进行了以下设置

<configuration>
<system.web>
<globalization culture="auto:en-US" uiCulture="fr" />
</system.web>
</configuration>

我正在使用此博客作为参考 https://weblog.west-wind.com/posts/2014/Mar/27/Auto-Selecting-Cultures-for-Localization-in-ASPNET#ASP.NETNativeSupportforAutoLocaleSwitching

但我没有WebUtils ...... 建议我一个博客和一些想法..

2 个答案:

答案 0 :(得分:1)

您不应该使用UserLanguages来强化文化。相反,您应该put the culture in the URL,它允许用户选择使用哪种文化。

如果您的网站面向互联网,这意味着您的每种文化都将被编入索引并可以使用母语进行搜索。如果您的网站取决于浏览器的UserLanguages设置,那么您的非默认文化将不会被编入搜索索引。

  

真实故事

     

我将浏览器的主页设置为MSN已有好几年了。然而,当我突然搬到泰国时,页面以泰语显示。那时,我读不懂泰语。

     

更糟糕的是,没有(明显的)方法从用户界面中选择语言。当我尝试将网址更改为en-us时,它会将我重定向回泰语页面。我找了很长时间,但找不到将页面切换回英文的解决方案。

     那是7年前的事。从那时起,我的主页已设置为Google。最近,我尝试使用MSN网站,仍然没有办法将其切换为英文。

     

重点:始终让用户选择要查看的语言。

答案 1 :(得分:0)

您需要在Global.asax中添加此功能。它将获得文化。

protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
    {
        string culture = null;
        var request = HttpContext.Current.Request;
        string cultureName = null;

        // Attempt to read the culture cookie from Request
        var cultureCookie = request.Cookies["_culture"];

        if (cultureCookie != null)
            cultureName = cultureCookie.Value;
        else if (request.UserLanguages != null)
            cultureName = request.UserLanguages[0]; // obtain it from HTTP header AcceptLanguages

        culture = !string.IsNullOrEmpty(request.QueryString["culture"])
            ? request.QueryString["culture"]
            : cultureName;

        if (culture == null) return;

        var cultures =
            CultureInfo.GetCultures(CultureTypes.SpecificCultures);
        if (cultures.Any(cultureData => cultureData.Name == cultureName))
        {
            var cultureInfo = CultureInfo.GetCultureInfo(culture);
            Thread.CurrentThread.CurrentCulture = cultureInfo;
            Thread.CurrentThread.CurrentUICulture = cultureInfo;
        }
        else
        {
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-IN");
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-IN");
        }
    }
相关问题