多语言网站不改变语言

本文关键字:语言 改变 网站 | 更新日期: 2023-09-27 18:14:30

我的网站必须是英语和西班牙语,但用户应该能够在他们的个人资料页面选择语言。

有这样的结构。http://screencast.com/t/ArrNy8yDChM

在搜索输入中我有这个

         <input type="text" placeholder="@Resource.SearchBoxWatermark" class="form-control" name="top-search" id="top-search">

然后我有一个配置文件编辑视图

@{
    ViewBag.Title = "Profile";
    Layout = "~/Areas/GlobalAdmin/Views/Shared/_LayoutGlobalAdmin.cshtml";
}
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <div class="wrapper wrapper-content">
        <div class="row animated fadeInRight">
            <div class="col-md-4">
                <div class="ibox float-e-margins">
                    <div class="ibox-title">
                        <h5>Profile Detail</h5>
                    </div>
                    <div>
                        <div class="ibox-content no-padding border-left-right">
                            <img alt="image" class="img-responsive" src="~/Images/profile_big.jpg">
                        </div>
                        <div class="ibox-content profile-content">
                            <h4><strong>Monica Smith</strong></h4>
                            <p><i class="fa fa-map-marker"></i> Riviera State 32/106
                            </p>
                            <h5>
                                About me
                            </h5>
                            <p>
                                Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitat.
                            </p>
                            <label class="radio-inline">@Html.RadioButton("Language", "English") English</label>
                            <label class="radio-inline">@Html.RadioButton("Language", "Spanish") Spanish</label>
                            <br/>
                            <input type="submit" value="Update" class="btn btn-primary"/>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
}
@{Html.RenderPartial("~/Areas/GlobalAdmin/Views/Shared/_Toastr.cshtml");}

和配置文件编辑操作:

[HttpPost]
        public async Task<ActionResult> Edit(FormCollection formCollection)
        {
            try
            {
                var client = AuthenticationHelper.GetActiveDirectoryClient();
                var user = (Microsoft.Azure.ActiveDirectory.GraphClient.User) await client.Users.GetByObjectId(ClaimsPrincipal.Current.Identities.First().Name).ExecuteAsync();
                var extPropLookupNameLanguage = $"extension_{SettingsHelper.ClientId.Replace("-", "")}_{"Language"}";
                user.SetExtendedProperty(extPropLookupNameLanguage, formCollection["Language"]);    
                await user.UpdateAsync();
                try
                {
                    string culture = string.Empty;
                    if (formCollection["Language"].ToString() == "English")
                    {
                        culture = "en-US";
                    }
                    else if (formCollection["Language"].ToString() == "Spanish")
                    {
                        culture = "es-CO";
                    }
                    var cultureInfo = new CultureInfo(culture);
                    Thread.CurrentThread.CurrentUICulture = cultureInfo;
                    Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureInfo.Name);
                    HttpCookie langCookie = new HttpCookie("culture", culture);
                    langCookie.Expires = DateTime.Now.AddYears(1);
                    System.Web.HttpContext.Current.Response.Cookies.Add(langCookie);
                    var toastrSuccess = "Perfil actualizado satisfactoriamente";
                    return RedirectToAction("Edit", new { toastrSuccess = toastrSuccess });
                }
                catch (Exception ex)
                {
                    var toastrError = ex.Message;
                    return RedirectToAction("Edit", new { toastrError = toastrError });
                }
            }
            catch (Exception ex)
            {
                ViewBag.toastrError = ex.Message;
                return RedirectToAction("Edit", new { toastrError = ex.Message });
            }
        }

然而,当我在单选按钮中选择西班牙语时,搜索输入水印不会更改为西班牙语,如下所示:

http://screencast.com/t/78YqMeMvx4qg

我在这里错过了什么?

多语言网站不改变语言

原因是您正在为当前线程(执行您的Edit操作的线程)设置线程uicculture和culture。最后,您将返回一个重定向,它基本上返回一个302状态码到客户端与您的重定向操作的URL。一旦客户端接收到它,它会向这个URL发出额外的请求,但是这个请求是由从线程池中获取的任意线程处理的。这个线程UI文化没有设置为西班牙语,这就是你的资源无法工作的原因。你需要做的是添加一些代码来解析每个传入请求的语言cookie(以防你为整个应用程序选择一种语言)。

你可以通过多种方式实现它:

1)实现一个IHttpModule,并在BeginRequest: 中设置文化
   void context_BeginRequest(object sender, EventArgs e)
   {
      if (HttpContext.Current.Request.Cookies["culture"] != null)
      {
        HttpCookie cookie = HttpContext.Current.Request.Cookies["culture"];
        string lang = cookie.Value;
        var culture = new System.Globalization.CultureInfo(lang);
        Thread.CurrentThread.CurrentCulture = culture;
        Thread.CurrentThread.CurrentUICulture = culture;
      }
   }

2)覆盖onactionexecution处理器在你的基本控制器:

 protected override void OnActionExecuting(ActionExecutingContext filterContext)
 {
      if (HttpContext.Current.Request.Cookies["culture"] != null)
      {
        HttpCookie cookie = HttpContext.Current.Request.Cookies["culture"];
        string lang = cookie.Value;
        var culture = new System.Globalization.CultureInfo(lang);
        Thread.CurrentThread.CurrentCulture = culture;
        Thread.CurrentThread.CurrentUICulture = culture;
      }
      base.OnActionExecuting(filterContext);           
  }