}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Redirect("ChangeLanguage.aspx?Language=" + DropDownList1.SelectedValue + "&url=" + Server.UrlEncode(Request.Url.PathAndQuery), true);
}
建立中间页 ChangeLanguage.aspx
public partial class ChangeLanguage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Cookies["Language"].Value = Request["Language"];
Response.Cookies["Language"].Expires = DateTime.Now.AddDays(1000);
Response.Redirect(Server.UrlDecode(Request["url"]));
}
}
public class BasePage : System.Web.UI.Page
{
/// <summary>
/// 本地化
/// </summary>
protected override void InitializeCulture()
{
if (Request.Cookies["Language"] != null && Request.Cookies["Language"].Value != null && Request.Cookies["Language"].Value != "")
{
setCulture();
}
else
{//设置Cookie
Response.Cookies["Language"].Value =(Request.Headers["accept-language"].Split(",".ToCharArray())[0]);
Response.Cookies["Language"].Expires = DateTime.Now.AddDays(1000);
setCulture();
}
base.InitializeCulture();
}
private void setCulture()
{
try
{
String selectedLanguage = Request.Cookies["Language"].Value;
UICulture = selectedLanguage;
Culture = selectedLanguage;
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture(selectedLanguage);
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(selectedLanguage);
}
catch
{
Response.Cookies["Language"].Expires = DateTime.Now.AddDays(-1);
}
}
建立演示页面default.asp
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<uc1:WebUserControl id="WebUserControl1" runat="server">
</uc1:WebUserControl><br />
<asp:Literal ID="Literal1" runat="server" Text="<%$ Resources:ChangeLanguage, Lang1%>" />
<asp:Button ID="Button1" runat="server" Text="<%$ Resources:ChangeLanguage, Lang2 %>" />
</form>
</body>
</html>
default.aspx.cs
public partial class _Default : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
最后建立资源文件
ChangeLanguage.resx 设置字段:Lang1 值:中文;字段:Lang2 值:英文
复制ChangeLanguage.resx把他重命名为ChangeLanguage.en.resx然后分别把Lang1值该为chinese;Lang2的值该为Englist
运行以下 Ok了!