Asp.net: Chinese characters lost due to Cookie transcoding Problems

Source: Internet
Author: User
Because asp.net uses the UTF-8 text encoding to display GB2312 Chinese, so sometimes there will be garbled characters, especially when cookies, and even when we are on the web. <globalization requestEncoding = "gb2312" responseEncoding = "gb2312"/> after this setting in config will cause our Chinese cookies to become garbled characters, leading to invalid cookies, therefore, convert cookies Into the UTF-8 format: the code is as follows:/*** // <summary>
/// Set 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 );
}

Use this function when reading cookies:

/** // <Summary>
/// UTF encode the cookie
/// Author: jake
/// Bt: 080414
/// </Summary>
/// <Param name = "str"> </param>
/// <Returns> </returns>
Public static string GetCookid (string str)
{
Encoding stre = Encoding. GetEncoding ("UTF-8 ");
Return HttpUtility. UrlDecode (str, stre );
}

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

So far, the loss of Chinese Character cookies can be solved!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.