解決方案原理:
ASP.Net本地化支持
通過 CultureInfo 類可以訪問區域設置的屬性。
此外,ASP.Net 基於每個線程和請求跟蹤默認區域性的兩個屬性:用於區域設置相關函數默認值的 CurrentCulture,
和用於區域設置特定的資源數據查找的 CurrentUICulture。
解決方案主要包含幾個部分組成:
1:客戶設置語言的控件,一般會包含在每個頁面,使得用戶可以隨時切換區域
控件ascx代碼
<ASP:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndExchanged">
<asp:ListItem Text="English Version" Value="en-US"></ASP:ListItem>
<asp:ListItem Text="中 文 版" Value="zh-CN"></ASP:ListItem>
</ASP:DropDownList>
控件CS事件代碼
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack){
if (Request.Cookies[Settings.Default.Cookies_Language] == null || Request.Cookies[Settings.Default.CookIEs_Language].Value == "")
{
foreach (ListItem li in DropDownList1.Items)
{
if (li.Value == "")
li.Selected = true;
}
}
else
{
foreach (ListItem li in DropDownList1.Items)
{
if (li.Value.ToLower() == Request.Cookies[Settings.Default.CookIEs_Language].Value.ToLower())
li.Selected = true;
}
}
}
}
protected void DropDownList1_SelectedIndExchanged(object sender, EventArgs e)
{
Response.Redirect("~/ChangeLanguage.ASPx?Language=" + DropDownList1.SelectedValue + "&url=" + Server.UrlEncode(Request.Url.PathAndQuery) ,true);
}ChangeLanguage中間頁面代碼:
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"]));
}
}
2:在每頁加載時會判斷當前用戶選擇的區域,一般在頁面的基類中實現比如類名:BasePage。
當用戶初次進入網站識別客戶端浏覽器,
當用戶曾經選擇了區域,加載選擇區域
/**//// <summary>
/// 本地化
/// </summary>
protected override void InitializeCulture()
{
if (Request.Cookies[Settings.Default.Cookies_Language] != null && Request.Cookies[Settings.Default.Cookies_Language].Value != null && Request.Cookies[Settings.Default.CookIEs_Language].Value != "")
{
setCulture();
}
else
{//設置CookIE
Response.Cookies[Settings.Default.CookIEs_Language].Value =
(Request.Headers["accept-language"].Split(",".ToCharArray())[0]);
Response.Cookies[Settings.Default.CookIEs_Language].Expires = DateTime.Now.AddDays(1000);
setCulture();
}
base.InitializeCulture();
}
private void setCulture()
{
try
{
String selectedLanguage = Request.Cookies[Settings.Default.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 //( Exception ex )
{
Response.Cookies.Clear();// [Settings.Default.CookIEs_Language].d
//throw;
}
}
3:當然是為每個頁面准備資源文件。
這個是個體力活,
ASPNET.ascx.en.resx 表示英文的
ASPNET.ascx.zh.resx 這個表示中文的,當然還可以分為更加細的區域,比如zh-CN/zh-HK/zh-TW
4:當然要記得,把你的頁面都要繼承你的基類
public partial class Index : PageBase