读cookies中的中文用户名问题?
现在在改公司OA中的一个Bug,在OA系统中中文用户名不能登陆,跟踪发现是在读cookies中的中文用户名时出错,而用英文的就不会出错。
刚开以为是编码问题,但Web.Config中不论配置那种编码都不行(GB2312,UTF-8),在网上搜索说是,编码与解码要统一,我只是在ASP.NET中读写,不是ASP与ASP.NET交替,也不是在1.1与2.0之间。
我用的方法是:
一、写Cookies
HttpCookie myCookie = new HttpCookie("userinfo");
myCookie["UserID"] = UserID;
myCookie["ActiveNodeID"] = "0";
myCookie["Username"] = txtUsername.Text.ToString().Trim();
myCookie["Test"] = "Testing";
myCookie.Expires = new DateTime(2010,1,1);
Response.AppendCookie(myCookie);
----------------------------------------------------
写出的Cookies为:
userinfo
UserID=15&ActiveNodeID=0&Username=柳志&Test=Testing
localhost/
1024
1313521664
30050866
3127664
29894241
*
------------------------------------------------
读cookies
HttpCookie cookie = Request.Cookies["userinfo"];
string Username = cookie.Values["Username"];
从程序跟踪看Username = "-";一横比这要短些,复制到txt文件中是一个黑的小方块,保存文件后就变为问号(?)
二、写cookies
public static void Set(string Key,string Value,bool SaveFlag)
{
System.Text.Encoding objEnc = System.Text.Encoding.GetEncoding("GB2312");
HttpCookie cookie = new HttpCookie(Key, System.Web.HttpUtility.UrlDecode(Value, objEnc));
cookie.Path="/";
if(SaveFlag)
{
cookie.Expires = new DateTime(2010,1,1);
}
System.Web.HttpContext.Current.Response.AppendCookie(cookie);
}
写出来的cookies为:
UserID
15
localhost/
1024
1313521664
30050866
2106975776
29894244
*
ActiveNodeID
0
localhost/
1024
1313521664
30050866
2107285776
29894244
*
Username
柳志
localhost/
1024
1313521664
30050866
2107445776
29894244
*
读cookies:
public static string Get(string Key)
{
string s = string.Empty;
if(System.Web.HttpContext.Current.Request.Cookies[Key] != null)
{
s = System.Web.HttpContext.Current.Server.UrlEncode
(System.Web.HttpContext.Current.Request.Cookies[Key].Value);
//些时读出的值为:"%3f"
System.Text.Encoding objEnc = System.Text.Encoding.GetEncoding("GB2312");
s = System.Web.HttpUtility.UrlDecode(s, objEnc);
//到这里转码后又变成问号("?")
//s = System.Web.HttpContext.Current.Request.Cookies[Key].Value;
}
return s;
}
同事中也没人能理解为什么会出现这种情况
在网上找了两天也没能搜到解决的办法,没多少时间再搜索了,只能求求可爱的你们给我点提示了。
<globalization requestEncoding="GB2312" responseEncoding="GB2312" fileEncoding="GB2312" culture="zh-cn"/>这是Web.config中的一句。分不是主要的,能学到知识才是重要的。