Home  >  Article  >  Backend Development  >  .net uses cookies to generate garbled characters

.net uses cookies to generate garbled characters

巴扎黑
巴扎黑Original
2016-12-19 15:47:151420browse

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn