原文 www.cnblogs.com/xdotnet/archive/2006/09/27/Get_right_cookie_value.html
今天有个***妹问我:在Asp.net的HttpCookie中写入汉字,读取值为 什么全是乱码?其实这是因为文字编码而造成的,汉字是两个编码,所以才会搞出这么个乱码出来!其实解决的方法很简单:只要在写入Cookie时,先将其用 Url编码,然后再写入,当我们读取时再解码就OK了,希望更多的***妹能解决它,呵呵!
例子:
Cookie的写入:
1
HttpCookie cookie
=
new
HttpCookie(
"
Simple
"
);
2 cookie.Values.Add( " Simple1 " ,HttpUtility.UrlEncode( " 大叔,你好! " ));
3 cookie.Values.Add( " Simple2 " , " English is OK!Nothing we should do! " );
4 Response.AppendCookie(cookie);
2 cookie.Values.Add( " Simple1 " ,HttpUtility.UrlEncode( " 大叔,你好! " ));
3 cookie.Values.Add( " Simple2 " , " English is OK!Nothing we should do! " );
4 Response.AppendCookie(cookie);
Cookie的读取:
1
HttpCookie cookie
=
Request.Cookies[
"
Simple
"
];
2 string simple1 = HttpUtility.UrlDecode(cookie[ " Simple1 " ]);
3 string simple2 = cookie[ " Simple2 " ];
2 string simple1 = HttpUtility.UrlDecode(cookie[ " Simple1 " ]);
3 string simple2 = cookie[ " Simple2 " ];
这样simple1="大叔,你好!";simple2="English is OK!Nothing we should do!";
很简单吧!!!