. NET use of cookies to generate garbled problems

Source: Internet
Author: User
This is the problem I'm actually having.

In the local test is good, the results published to IIS, the read out of the cookie is garbled

The first use of a very silly way, is to put a Chinese-containing cookie at the end of the deposit, this solves at least one problem, that does not contain Chinese cookies can read normally, it is possible that the Chinese garbled cause the cookie byte reading disorder

Later improved, found the online method, but also to you paste up, for everyone to reference

To prevent this article from being erased, I glued it down.

Here is the code to write the cookie

[CSharp] View plain copy

HttpCookie cookie = new HttpCookie ("username");

Cookies. Value = "Zhang San, 14,images/1.jpg";

Cookies. Expires = DateTime.Now.AddDays (1);

RESPONSE.COOKIES.ADD (cookie);

Here is the code to read the cookie

[CSharp] View plain copy

if (request.cookies["username"]!=null)

{

String username = request.cookies["username"]. Value;

Response.Write (username);

}

Sometimes the Chinese part of the value of the cookie that is read may be garbled, and whatever causes it, we can solve it by coding

Change the code above to write a cookie

[CSharp] View plain copy

HttpCookie cookie = new HttpCookie ("username");

Cookies. Value = Httputility.urlencode ("Zhang San, 14,images/1.jpg", Encoding.GetEncoding ("utf=8"));

Cookies. Expires = DateTime.Now.AddDays (1);

RESPONSE.COOKIES.ADD (cookie);

Change the code above to read the cookie

[CSharp] View plain copy

if (request.cookies["username"]!=null)

{

String Username =httputility.urldecode (request.cookies["username"]. Value,encoding.getencoding ("UTF-8"));

Response.Write (username);

}

Like this, when the cookie is stored and read using UTF8 way, it will no longer garbled, whether it is on the server or local line, tried

  • Related Article

    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.