Home > Article > Backend Development > .net uses cookies to generate garbled characters
This is a problem I actually encountered
It was fine when tested locally. However, when the results were posted to iis, the read cookie became garbled.
I used a very stupid way at the beginning, which was to put the cookie containing Chinese characters The cookie is placed at the end before being saved. This at least solves one problem, that is, cookies that do not contain Chinese characters can be read normally. It may be that the garbled Chinese characters cause the cookie bytes to be read garbled
It was later improved and I searched online The method is also pasted for your reference
In order to prevent this article from being deleted, I have pasted it down.
The following is the code to write the cookie
[csharp] view plain copy
HttpCookie cookie = new HttpCookie("username");
Cookie.Value = "Zhang San,14,images/1.jpg";
cookie.Expires use with ’ ’ s ’ ’ s ’s out through off ’s ’ out through out out out out out out out out out out Through out Through Over While After ‐ ‐ Cookie.Expires – Request.Cookies[ "username"]!=null)
The Chinese part may be garbled. No matter what the cause is, we can solve it through coding
Change the code that writes the cookie above
[csharp] view plain copy
HttpCookie cookie = new HttpCookie("username"); . Cookie.value = httputility.urlencode ("Zhang San, 14, Images/1.jpg", Encoding.Getencoding ("UTF = 8");
cookie.expires = s (1);
username =HttpUtility.UrlDecode(Request.Cookies["username"].Value,Encoding.GetEncoding("UTF-8"));
Response.Write(username); Hedu Use utf8 when fetching cookies, and there will be no garbled characters. It works whether it is on the server or locally. I have tried it