日期:2014-05-18  浏览次数:20743 次

cookies 乱码问题
.NET2005   .NET   Cookies取得和设置出现乱码怎么办

------解决方案--------------------
设置Cookies[ "xx "] = Server.UrlEncode( "中文 ")
取得Server.UrlDecode(Cookies[ "xx "])
------解决方案--------------------
private string getCookie(string key) {

return getCookie(key, null);


}
private string getCookie(string key,string defaultValue)
{

HttpCookieCollection cookies;
cookies = Request.Cookies;

HttpCookie cookie;

cookie = cookies.Get(key);
if (cookie!=null )
{
String valueTmp;
valueTmp = cookie.Value;
valueTmp = System.Web.HttpUtility.UrlDecode(valueTmp, Encoding.UTF8);

return valueTmp;
}
else
{
return defaultValue;
}

}

private void setCookie(string key, string value) {

HttpCookieCollection cookies;
HttpCookie cookie;
cookies = Response.Cookies;
cookie = cookies.Get(key);

String valueTmp = value;
//valueTmp = Encoding.UTF8.GetString(System.Text.Encoding.UTF8.GetBytes(value));

valueTmp = System.Web.HttpUtility.UrlEncode(valueTmp, Encoding.UTF8);
if (cookie !=null )
{
cookie.Value =valueTmp ;
cookie.Expires = DateTime.Now.AddMonths(1);

//System.Text.Encoding.UTF8.GetString(
//Debug.Print(valueTmp );
cookies.Add(cookie);


}
else
{

cookie = new HttpCookie(key, valueTmp);
cookie.Expires = DateTime.Now.AddMonths(1);
//cookie.Value =value ;

cookies.Add(cookie);

}
}