Let's take a look at two pieces of code:
1.
[Csharp]
// Output the Cookie on the output page of the current request
HttpCookie cookie = new HttpCookie ("ClientId", loginResult. TValue. Info. Code. ToString ());
Cookie. Expires = DateTime. Now. AddMinutes (20 );
This. Response. Cookies. Add (cookie );
2.
[Csharp]
HttpCookie cookie = new HttpCookie ("ClientId", loginResult. TValue. Info. Code. ToString ());
Cookie. Expires = DateTime. Now. AddMinutes (ExpiresMinutes );
Cookie. HttpOnly = true;
Cookie. Path = "/";
HttpContext. Current. Response. Cookies. Add (cookie );
There is no difference.
When executing the 2nd types of code, I can use the network information provided by IE9 to find the Cookie value as ClientId. I can't get the Cookie value with js.
(These two codes can obtain cookies in the background)
By the way, the code for JS to retrieve cookies is as follows:
[Javascript]
Function getCookie (objName) {// obtain the cookie value of the specified name
Debugger;
Var arrStr = document. cookie. split (";");
For (var I = 0; I <arrStr. length; I ++ ){
Var temp = arrStr [I]. split ("= ");
If (temp [0] = objName) return unescape (temp [1]); // The url is encoded, so it should be decoded.
}
}
Why?
Note: you cannot obtain Cookies written in the background of the server by using javascript scripts on the client. It is very likely that the HttpOnly attribute is set to true on the server.
The HttpOnly attribute of the HTTP Cookie object in ASP. Net specifies whether a Cookie can be accessed through client scripts. The value true cannot be accessed through client scripts; otherwise, the value false. The default value is false. This attribute does not completely prevent the client from obtaining cookies locally, but it can increase the difficulty of directly obtaining cookies through scripts.
Microsoft Internet Explorer version 6 Service Pack 1 and later support the Cookie attribute HttpOnly.
The problem persists.
Author: Deng Fuyong