Both javascript cookies and asp.net cookies point to the same thing. Not much nonsense.
1. Use asp.net to write cookies in the background, and use javascript to read
Protected void Page_Load (object sender, EventArgs e) {HttpCookie cookie = new HttpCookie ("MyCook"); // The name DateTime dt = DateTime of the First-made and set Cookie. now; TimeSpan ts = new TimeSpan (0, 0, 1, 0, 0); // The expiration time is 1 minute cookie. expires = dt. add (ts); // set the expiration time // string tmp = System. web. httpUtility. urlEncode ("Chinese", System. text. encoding. UTF8); cookie. values. add ("userid", "123"); cookie. values. add ("userid2", "456"); Response. appendCookie (cookie );}
Reading javascript at the front end
<script type="text/javascript"> var allcookies = document.cookie; function test() { //alert(decodeURIComponent(allcookies)); alert(allcookies); } </script>
The front-end can obtain data normally.
Mybook = userid = 123 & userid2 = 456
But note that when asp.net inputs Chinese, it should be converted into a UTF-8 code
Protected void Page_Load (object sender, EventArgs e) {HttpCookie cookie = new HttpCookie ("MyCook"); // The name DateTime dt = DateTime of the First-made and set Cookie. now; TimeSpan ts = new TimeSpan (0, 0, 1, 0, 0); // The expiration time is 1 minute cookie. expires = dt. add (ts); // set the expiration time string tmp = System. web. httpUtility. urlEncode ("Chinese", System. text. encoding. UTF8); cookie. values. add ("userid", tmp); cookie. values. add ("userid2", "Chinese"); Response. appendCookie (cookie );}
Garbled characters are obtained when javascript is directly read at the front end!
MyCook = userid = % e4 % b8 % ad % e6 % 96% 87 & userid2 = Juan Xiao
Therefore, when entering Chinese characters
System. Web. HttpUtility. UrlEncode ("Chinese", System. Text. Encoding. UTF8 );
When reading with javascript
decodeURIComponent(allcookies)
Let's look at the example (you can use decodeURIComponent to read Chinese correctly.
decodeURIComponent(document.cookie);
MyCook = userid = Chinese & userid2 = Juan Xiao
2. Use javascript to write cookies on the front end, And asp.net reads
Front-end code
document.cookie = "MyCook=userid=123&userid2=456"
Background code
If (Request. Cookies ["MyCook"]! = Null) {// Response. write ("the key value of Cookie is userid:" + Request. cookies ["MyCook"] ["userid"]); // The whole line // Response. write ("the key value of Cookie is userid2" + Request. cookies ["MyCook"] ["userid2"]); Response. write (Request. cookies ["MyCook"]. value); // output all values}