Cookite 出现乱码

此文转载自opent.cn:http://www.opent.cn/a/0912/2135.shtml

因为asp.net使用UTF-8的文字编码来显示GB2312的中文,所以有的时候会出现乱码,尤其在cookies的时候,

更甚至是我们在web.config中这样设置之后<globalization requestEncoding="gb2312" responseEncoding="gb2312"/>,会导致我们的中文cookie变成乱码,从而导致cookies无效,因此要将cookies转化成UTF-8的格式:

代码如下:


/**//// <summary>
/// 设置 Cookie
/// </summary>
/// <param name="lxfs"></param>
/// <param name="expiresDays"></param>
public static void SetCookie(string key, string value, int expiresDays)
{
DateTime expires = DateTime.Now.AddDays(expiresDays);
HttpCookie MyCookie = new HttpCookie(key);
MyCookie.Domain = ".yourdomain.com";
MyCookie.Value = HttpUtility.UrlEncode(value);
MyCookie.Expires = expires;
HttpContext.Current.Response.Cookies.Add(MyCookie);
}
读取cookie的时候使用这个函数:


/**//// <summary>
/// 对cookie进行UTF编码
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string GetCookid(string str)
{
Encoding stre = Encoding.GetEncoding("UTF-8");
return HttpUtility.UrlDecode(str,stre);
}

如:

GetCookid(HttpContext.Current.Request.Cookies["sswoo_user"].Value)

你可能感兴趣的:(OO)