在说到ASP.NET多语系(1)---前端页面多语系设置之后,就是要实现在后端设置具体的更改系统语言环境了。
首先添加Global.asax文件,直接选择不用修改:
在Application_BeginRequest事件:
protected void Application_BeginRequest(object sender, EventArgs e) { string strUserLanaguage = "zh-TW";//默认语系 if (null != Request.Cookies["lanaguage"]) { strUserLanaguage=Request.Cookies["lanaguage"].Value;//设置语系 } else { if (null != Request.UserLanguages) strUserLanaguage = Request.UserLanguages[0];//浏览器默认语系 } SetApplicationLanaguage(strUserLanaguage); } #region 设定系统显示语言 /// <summary> /// 设定系统显示语言 /// </summary> /// <param name="userLanaguage">语系简称</param> private void SetApplicationLanaguage(string userLanaguage) { System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture(userLanaguage); System.Threading.Thread.CurrentThread.CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentCulture; } #endregion
然后在登陆页面的一个下拉框,形如:
<asp:DropDownList ID="ddlLanaguage" runat="server" AutoPostBack="true" onselectedindexchanged="ddlLanaguage_SelectedIndexChanged"> <asp:ListItem Text="简体" Value="zh-CN"></asp:ListItem> <asp:ListItem Text="繁体" Value="zh-TW"></asp:ListItem> <asp:ListItem Text="英文" Value="en-us"></asp:ListItem> </asp:DropDownList>
后台事件:
protected void ddlLanaguage_SelectedIndexChanged(object sender, EventArgs e) { HttpCookie aHttpCookie = new HttpCookie("lanaguage"); aHttpCookie.Value = ddlLanaguage.SelectedValue; Response.Cookies.Remove("lanaguage"); Response.Cookies.Add(aHttpCookie); SetApplicationLanaguage(aHttpCookie.Value);
HttpCookie oHttpCookie = new HttpCookie("lanIndex");
oHttpCookie.Value = ddlLanaguage.SelectedIndex.ToString();
Response.Cookies.Add(oHttpCookie);
Response.Redirect(Request.Url.ToString());
} #region 设定系统显示语言 private void SetApplicationLanaguage(string userLanaguage) { System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture(userLanaguage); System.Threading.Thread.CurrentThread.CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentCulture; } #endregion
在Page_Load事件中:
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { //下拉框語系設置 if ( null != Request.UserLanguages) { if ("zh-CN" == Request.UserLanguages[0].ToString()) { ddlLanaguage.SelectedIndex = 0; } else if ("zh-TW" == Request.UserLanguages[0].ToString()) { ddlLanaguage.SelectedIndex = 1; } else //if("en-US" == Request.UserLanguages[0].ToString()) { ddlLanaguage.SelectedIndex = 2; } } if (null != Request.Cookies["lanIndex"]) { ddlLanaguage.SelectedIndex = Convert.ToInt32(Request.Cookies["lanIndex"].Value); }
//注意:如果浏览器未设置语系,那么页面会根据操作系统语系显示,此处未处理。 建议:使用在下拉框中添加一个空选项 } }
只不过仍有问题:
A.点击下拉框网页不会及时的变更为已选择的语系而是上次选择的语系(比如第一次浏览为简体,然后选择英文页面无变化,第二次选择繁体显示为英文,再选择简体显示为繁体,在选择繁体显示为简体。。。)
问题已解决。