多语言网站不改变语言

时间:2015-09-25 17:00:39

标签: c# asp.net asp.net-mvc asp.net-mvc-4 asp.net-mvc-5

我的网站必须使用英语和西班牙语,但用户应该可以在个人资料页面中选择语言。

我有这个结构。 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

我在这里缺少什么?

1 个答案:

答案 0 :(得分:1)

原因是您只为当前线程(执行Edit操作的线程)设置线程UICulture和Cultue。最后,您将返回一个重定向,它基本上返回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)覆盖基本控制器中的OnActionExecuting处理程序:

 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);           
  }