我有一个asp.net Web应用程序,其中一个下拉框包含语言首选项(英语,法语)。当我选择法语时,我会将cookie写成以下内容 -
protected void ddChoice_SelectedIndexChanged(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("pref");
cookie.Value = ddChoice.SelectedValue;
cookie.Expires = DateTime.Now.AddYears(1);
Response.SetCookie(cookie);
Thread.CurrentThread.CurrentCulture = new CultureInfo(ddChoice.SelectedValue);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(ddChoice.SelectedValue);
Server.Transfer(Request.Path);
}
并在开始请求中阅读此cookie,如下所示 -
protected void Application_BeginRequest(object sender, EventArgs e)
{
string lang = string.Empty;//default to the invariant culture
HttpCookie cookie = Request.Cookies["pref"];
if (cookie != null && cookie.Value != null && !string.IsNullOrEmpty(cookie.Value.Trim()))
lang = cookie.Value;
if (string.IsNullOrEmpty(lang))
lang = "en-US";
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(lang);
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang);
}
这次如果我检查浏览器cookie,它会被正确设置为“fr-FR”。但在此之后,当我转到主页并刷新此页面时,cookie将设置为空白。
我不确定它会被覆盖的地方。有什么帮助吗?
答案 0 :(得分:0)
我认为ddChoice_SelectedIndexChanged
事件是使用空SelectedValue
生成的,因此您的Cookie为空。尝试将断点放在方法中或将其注释掉。
答案 1 :(得分:0)
作为步骤4中的测试用例,当您点击F5页面时,获得回发并使用默认的顶级语言设置语言的语言下拉列表。
为此,您需要在控件或页面中编写一个函数,其中放置了您设置选定语言的语言下拉列表。
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
setLangDropdown();
}
}
private void setLangDropdown()
{
HttpCookie cookie = Request.Cookies["pref"];
string lang = string.Empty;
if (cookie != null && cookie.Value != null && !string.IsNullOrEmpty(cookie.Value.Trim()))
lang = cookie.Value;
if (!string.IsNullOrEmpty(lang))
ddChoice.SelectedValue = lang;
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("pref");
cookie.Value = ddChoice.SelectedValue;
cookie.Expires = DateTime.Now.AddYears(1);
Response.SetCookie(cookie);
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(ddChoice.SelectedValue);
Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(ddChoice.SelectedValue);
}