以下的理解可能不正确,是否正确待验证!
1.aspx
- protected void Page_Load(object sender, EventArgs e)
- {
- // 给会话添加一项
- Session.Add("ss", "ttttt");
- string cookie = "";
- string outcookie = "";
- string s2 = HttpWebResponsePost("http://host/test/2.aspx", "", "utf-8", cookie, out outcookie);
- Response.Write(s2);
- }
复制代码
2.aspx
- protected void Page_Load(object sender, EventArgs e)
- {
- Response.Write("request page... Session Count:" + Session.Count);
- Response.Write("<br>Session["ss"]=" + Session["ss"].ToString());
- }
复制代码
3.aspx
- protected void Page_Load(object sender, EventArgs e)
- {
- //请求3.aspx得到HTML
- string cookie = "";
- string outcookie = "";
- string s1 = HttpWebResponsePost("http://host/test/1.aspx", "", "utf-8", cookie, out outcookie);
- string cookie2 = outcookie;
- string s2 = HttpWebResponsePost("http://host/test/2.aspx", "", "utf-8", cookie2, out outcookie);
- Response.Write(s2);
- }
- public static string HttpWebResponsePost(string url, string postData, string encodeType, string cookie, out string outcookie)
- {
- Stream outstream = null;
- Stream instream = null;
- StreamReader sr = null;
- HttpWebResponse response = null;
- HttpWebRequest request = null;
- Encoding encoding = Encoding.GetEncoding(encodeType);
- byte[] data = encoding.GetBytes(postData);
- try
- {
- request = WebRequest.Create(url) as HttpWebRequest;
- CookieContainer cookieContainer = new CookieContainer();
- request.CookieContainer = cookieContainer;
- if (cookie != "")
- {
- request.CookieContainer.SetCookies(new Uri(url), cookie);
- }
- request.AllowAutoRedirect = true;
- request.Method = "POST";
- request.ContentType = "application/x-www-form-urlencoded";
- request.ContentLength = data.Length;
- outstream = request.GetRequestStream();
- outstream.Write(data, 0, data.Length);
- outstream.Close();
- response = request.GetResponse() as HttpWebResponse;
- instream = response.GetResponseStream();
- outcookie = request.CookieContainer.GetCookieHeader(new Uri(url));
- sr = new StreamReader(instream, encoding);
- string content = sr.ReadToEnd();
- HttpContext.Current.Response.Write(HttpContext.Current.Session["ss"]);
- return content;
- }
- catch (Exception ex)
- {
- outcookie = "";
- return string.Empty;
- }
- }
复制代码
1.aspx POST 2.aspx时,不显示Session值,看起来似乎丢了Session。
理解如下:当HTTPWEBREQUEST时POST 2.aspx 时,实现等于执行了一次无Session传值的2.aspx,不会显示Session值。但1.aspx的Session值已经传入了2.aspx。只是Response.Write("<br>Session[\"ss\"]=" + Session["ss"].ToString());不是传值Session后的值,所以不可能显示tttttt值。
当3.asp将outcookie传给新cookie2时,实际上2.aspx符合读取Session流的Session存在,故能读取Session[“tt”]
|