Cookie and understanding of the Session

  I believe that many small partners to engage in the development of BS, more or less will understand Cookie and Session these two objects, we used most places, it must belong to landing, after landing, the user information stored in the User Session inside, then as long as do not close the browser or exit manually, you can directly stay logged in, the user information stored in the Session at any time to get inside of.

  We know that the browser request is a request based on Http protocol, which is connectionless, stateless, client requests a server on a feedback, and this time the request and the next request without any relationship, that is, the server completely I do not know you two consecutive requests are sent.

  Cookie is stored in the client, while the Session is stored on the server, which we all know is one of the most basic common sense. That we first get to know about Cookie.

Directly on the code

1         public string SetCookie()
2         {
3 
4             HttpCookie myCookie = new HttpCookie("myCustomCookie", "abc");
5             myCookie.Expires = DateTime.Now.AddMinutes(1);
6             Response.Cookies.Add(myCookie);
7 
8             return "Cookie 设置成功";
9         }
View Code

Expires (expiration time) attribute is important, if not set, Cookie will be saved in the browser memory, cookie will be released after the browser is closed. If the expiration time is greater than the current time, Cookie will be saved on the hard disk of the client above, but before the expiration time, each request will bring the Cookie. If the expiration time is less than or equal to the current time, it is equivalent to delete the cookie.

  So what is the principle of Session realize Now, we write a method to test,

1         public string SetSession()
2         {
3             Session["loginUser"] = "mxj";
4             HttpContext.Session["loginPwd"] = "123";
5             HttpContext.Session.Timeout = 1;
6 
7 
8             return "Session 设置成功";
9         }
View Code

  We visited this method, the value is set to Session, and then we found every request, will bring a ASP.NET_SessionId of Cookie.

In fact Session function is based on this ASP.NET_SessionId the Cookie to achieve real, when we use the Session [ "loginUser"] = " mxj"; Session set a value, we can be understood as a Key, Value dictionary container, Key is current ASP.NET_SessionId the Cookie value  , value is this type System.Web.HttpSessionStateWrapper Session object, we operate on the Session of fact, this type of operation is an example of HttpSessionStateWrapper. So, we can be simply understood as the Session is actually to save the service in memory of ASP.NET_SessionId for the Key value of an object dictionary .

  According to the above understanding, if we set the value of the Session, and then ASP.NET_SessionId the cookie removed, we can not access the value of the Session, we have to verify, as follows

 

 1     public string SetSession()
 2         {
 3             Session["loginUser"] = "mxj";
 4             HttpContext.Session["loginPwd"] = "123";
 5             HttpContext.Session.Timeout = 1;
 6 
 7 
 8             return "Session 设置成功";
 9         }
10 
11         public string GetSession()
12         {
13             StringBuilder sb = new StringBuilder();
14 
15             HttpSessionStateBase sessionStateBase = HttpContext.Session;
16             for (int i = 0; i < sessionStateBase.Count; i++)
17             {
18                 sb.Append(sessionStateBase.Keys[i] + "" + sessionStateBase[i] + "<br/>");
19             }  
20 
21             return sb.ToString();            
22         }
23 
24         public string ClearCookie()
25         {
26             HttpCookieCollection newCollection = new HttpCookieCollection();
27             HttpCookieCollection cookieCollection = Request.Cookies;
28             for (int i = 0; i < cookieCollection.Count; i++)
29             {
30                 cookieCollection[i].Expires = DateTime.Now.AddMinutes(-1);
31                 newCollection.Add(cookieCollection[i]);
32 
33                 //Response.SetCookie(cookieCollection[i]);
34             }
35 
36             for (int j = 0; j < newCollection.Count; j++)
37             {
38                 Response.Cookies.Add(newCollection[j]);
39             }
40 
41             return "Cookie Clear成功";
42         }
View Code

 

Let's execution method SetSession, and then perform the method GetSession, we'll get the value of the Session

When you do this method, we must take this request by sending a cookie record, back when requested by reptiles simulation will be used

Then we perform the method ClearCookie clear all cookie, and then perform the method GetSession to acquire Session, without any result, (blank, no result, no screenshot).

The server memory value corresponding to the value of this ASP.NET_SessionId key is to continue to exist na, na or removed as a result?

We wrote a simple reptile to verify the results, as follows

  1         private void btnCatch_Click(object sender, EventArgs e)
  2         {
  3             var url = tbxUrl.Text;
  4             url = url.Trim();
  5 
  6             var cookie = tbxCookie.Text;
  7 
  8             var result = HttpHelper.DownloadUrl(url, cookie);
  9 
 10             tbxResult.Text = result;
 11         }
 12 
 13 
 14 
 15  public class HttpHelper
 16     {
 17         //private static Logger logger = new Logger(typeof(HttpHelper));
 18 
 19         /// <summary>
 20         /// 根据url下载内容  之前是GB2312
 21         /// </summary>
 22         /// <param name="url"></param>
 23         /// <returns></returns>
 24         public static string DownloadUrl(string url, string cookie = null)
 25         {
 26             return DownloadHtml(url, Encoding.UTF8, cookie);
 27         }
 28 
 29         //HttpClient--WebApi
 30 
 31         /// <summary>
 32         /// 下载html
 33         /// http://tool.sufeinet.com/HttpHelper.aspx
 34         /// HttpWebRequest功能比较丰富,WebClient使用比较简单
 35         /// </summary>
 36         /// <param name="url"></param>
 37         /// <returns></returns>
 38         public static string DownloadHtml(string url, Encoding encode, string cookie)
 39         {
 40             string html = string.Empty;
 41             try
 42             {
 43                 //https可以下载--
 44 
 45                 //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) =>
 46                 //{
 47                 //    return true; //总是接受  
 48                 //});
 49                 //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
 50 
 51                 HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;//模拟请求
 52                 request.Timeout = 30 * 1000;//设置30s的超时
 53                 //request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36";
 54                 //request.UserAgent = "User - Agent:Mozilla / 5.0(iPhone; CPU iPhone OS 7_1_2 like Mac OS X) App leWebKit/ 537.51.2(KHTML, like Gecko) Version / 7.0 Mobile / 11D257 Safari / 9537.53";
 55 
 56                 request.ContentType = "text/html; charset=utf-8";// "text/html;charset=gbk";// 
 57                                                                  //request.Host = "search.yhd.com";
 58 
 59                 request.Headers.Add("Cookie", cookie);
 60 
 61                 //request.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
 62                 //request.Headers.Add("Accept-Encoding", "gzip, deflate, sdch");
 63                 //request.Headers.Add("Referer", "http://list.yhd.com/c0-0/b/a-s1-v0-p1-price-d0-f0-m1-rt0-pid-mid0-kiphone/");
 64 
 65                 //Encoding enc = Encoding.GetEncoding("GB2312"); // 如果是乱码就改成 utf-8 / GB2312
 66 
 67                 //如何自动读取cookie
 68                 //request.CookieContainer = new CookieContainer();//1 给请求准备个container
 69                 using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)//发起请求
 70                 {
 71                     if (response.StatusCode != HttpStatusCode.OK)
 72                     {
 73                         //logger.Warn(string.Format("抓取{0}地址返回失败,response.StatusCode为{1}", url, response.StatusCode));
 74                     }
 75                     else
 76                     {
 77                         try
 78                         {
 79                             //string sessionValue = response.Cookies["ASP.NET_SessionId"].Value;//2 读取cookie
 80                             StreamReader sr = new StreamReader(response.GetResponseStream(), encode);
 81                             html = sr.ReadToEnd();//读取数据
 82                             sr.Close();
 83                         }
 84                         catch (Exception ex)
 85                         {
 86                             //logger.Error(string.Format($"DownloadHtml抓取{url}失败"), ex);
 87                             html = null;
 88                         }
 89                     }
 90                 }
 91             }
 92             catch (System.Net.WebException ex)
 93             {
 94                 if (ex.Message.Equals("远程服务器返回错误: (306)。"))
 95                 {
 96                     //logger.Error("远程服务器返回错误: (306)。", ex);
 97                     html = null;
 98                 }
 99             }
100             catch (Exception ex)
101             {
102                 //logger.Error(string.Format("DownloadHtml抓取{0}出现异常", url), ex);
103                 html = null;
104             }
105             return html;
106         }
107     }
View Code

这是一个winform的程序,抓取结果如下

在服务器还没有释放Session值之前,我们还是可以通过ASP.NET_SessionId的Cookie获取到对应的Session值。

  那么Session在服务器内存会保存多久呐,

我们会有一个Timeout的属性来设置它的过期时间(分钟为单位),如果没有设置,就默认配置文件为准,IIS的默认Session释放时间好像是20分钟。

 

以上是本人自己摸索所得,有什么不正确的地方,欢迎提出意见。

 

Guess you like

Origin www.cnblogs.com/xiaoZhang521/p/11287773.html