您应该首先检查cookie是否尚未定义..是否已经设置您无需再次设置..当用户选择一种新语言时,您应该重新定义它...一般算法,操作顺序是这样的
- 如果用户正在更改语言
- 将应用程序的语言更改为所选的
- 将其保存到 cookie
- 否则,如果之前的设置保留在 cookie 中
- 否则就是新的访问
- 将应用程序的语言更改为默认语言
- 将 cookie 设置为默认值
这应该在每个请求中进行评估..因为用户可以在任何页面更改语言..所以放置代码的正确事件应该是Application_BeginRequest
这是您的代码..我将语言参数保存在中,CurrentUICulture
因此不仅可以在应用程序的任何位置查询它,而且框架还使用它来自定义格式..我还假设用户可以传递一个名为lang
包含他想要的语言..
void Application_BeginRequest(object sender, EventArgs e)
{
//if user is changing language
if(!String.IsNullOrEmpty(HttpContext.Current.Request["lang"]))
{
String sLang = HttpContext.Current.Request["lang"] as String;
//change the language of the application to the chosen
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo(sLang);
//save it to cookie
HttpCookie myCookie = new HttpCookie("Language");
myCookie.Value = sLang;
myCookie.Expires = DateTime.Now.AddDays(1d);
HttpContext.Current.Response.Cookies.Add(myCookie);
}
//setting as been preserved in cookie
else if(HttpContext.Current.Request.Cookies["Language"])
{
//change the language of the application to the preserved
String sLang = HttpContext.Current.Request.Cookies["lang"].value as String;
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo(sLang);
}
else//new visit
{
//change the language of the application to the default
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-us");
//set cookie to the default
HttpCookie myCookie = new HttpCookie("Language");
myCookie.Value = "en-us";
myCookie.Expires = DateTime.Now.AddDays(1d);
HttpContext.Current.Response.Cookies.Add(myCookie);
}
}