Change Website UICulture

Change Website UICulture

前陣子花了不少功夫把網站的resource全部建置完畢,結果今天接到了需求單,說是希望登入的時候能直接變更語系,而不要透過IE去變更預設語系。

不過C#沒有像VB.NET直接提供變更語系的方法,而且變更語系的動作必須在每頁都要重設一次(不然會再被預設的蓋回來),加上系統並沒有base page,所以只好在Global.asax動手腳。

PS:變更語系一定要在UI畫出來之前先處理掉,因為我在page_preinit內還有處理讓theme因語系變更,所以就寫在同一個事件內了。

 

先來看看MSDN提供的範例:

 


protected override void InitializeCulture()
{
    if (Request.Form["ListBox1"] != null)
    {
        String selectedLanguage = Request.Form["ListBox1"];
        UICulture = selectedLanguage ;
        Culture = selectedLanguage ;

        Thread.CurrentThread.CurrentCulture = 
            CultureInfo.CreateSpecificCulture(selectedLanguage);
        Thread.CurrentThread.CurrentUICulture = new 
            CultureInfo(selectedLanguage);
    }
    base.InitializeCulture();
}

 

我的處理方式是在首頁增加選項,使用者登入之後把選擇的語系暫存到session裡面。

(不過我的網站本身有做session控管,登入時會產生一組驗證用的,如果session timeout會自動登出,

所以這理就不考慮session過期的問題...XD)

 

1.在公用區增加讀取語系設定的session

 


public static string SessionCulture
{
	get
	{
		if (HttpContext.Current.Session["CultureInfo"] == null)
			HttpContext.Current.Session["CultureInfo"] = CultureInfo.CurrentUICulture.IetfLanguageTag;
		return HttpContext.Current.Session["CultureInfo"].ToString();
	}
	set { HttpContext.Current.Session["CultureInfo"] = value; }
}

2.Login.aspx

 


private void changeLanguage()
{
	UserUtility.SessionCulture = LanguageDropDownList.SelectedValue;
}

3.Global.asax

 


protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
	HttpContext ctx = HttpContext.Current;
	//Response.Cache.SetCacheability(HttpCacheability.NoCache);
	Page p = (ctx.Handler as Page);
	if (p != null)
		p.PreInit += new EventHandler(Page_PreInit);
}

void Page_PreInit(object sender, EventArgs e)
{
	Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(UserUtility.SessionCulture);
	Thread.CurrentThread.CurrentUICulture = new CultureInfo(UserUtility.SessionCulture);
}

 

 

DotBlogs 的標籤:,

How to: Set the Culture and UI Culture for ASP.NET Web Page Globalization