.net程式控制post資料 需登陸後保持session的方法

來源:互聯網
上載者:User

標籤:程式   ati   spn   實現   throw   create   encoding   res   method   

最近在網上發現一些有意思的東西,想抓下來,被一個小問題給卡住了,程式如何發送post請求都沒法得到想要的結果,利用Firefox仔細研究下發現需要開啟一次頁面,再提交參數就ok,這就好辦了

學過網頁編程的都知道,session保持工作階段狀態,使得類似登陸功能可以連續保持。

但用程式發送post請求的時候,session就會丟失。

究其原因,還是要看session的原理。

其實session一般都有個sessionID儲存在cookie裡。

每次請求資料都會發送上次的cookie到伺服器。

PHP的一般為 PHPSESSIONID

asp.NET的好像是ASPNETSESSIONID

.....

其實只要把請求返回的sesionID給儲存下來。再賦值給下次要請求的request對象就OK了,只要此次session在服務端沒到期。

如下代碼實現:

private static CookieContainer m_Cookie = new CookieContainer();private static string post(string postURL, string postData, Encoding pageEncoding)        {            HttpWebRequest httpWebRequest;            HttpWebResponse httpWebResponse;            byte[] bytesToPost = pageEncoding.GetBytes(postData);            try            {                httpWebRequest = WebRequest.Create(postURL) as HttpWebRequest;                httpWebRequest.Method = "POST";                httpWebRequest.KeepAlive = true;                httpWebRequest.ContentType = "application/x-www-form-urlencoded";                httpWebRequest.CookieContainer = m_Cookie;//設定上一個訪問頁面的cookie 保持session                  httpWebRequest.ContentLength = bytesToPost.Length;                Stream requestStream = httpWebRequest.GetRequestStream();                requestStream.Write(bytesToPost, 0, bytesToPost.Length);//寫入post資訊                  requestStream.Close();                httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;                m_Cookie = httpWebRequest.CookieContainer;//訪問後更新cookie                  Stream responseStream = httpWebResponse.GetResponseStream();                string resData;                using (StreamReader resSR = new StreamReader(responseStream, pageEncoding))                {                    resData = resSR.ReadToEnd();                    resSR.Close();                    responseStream.Close();                }                return resData;            }            catch (Exception err)            {                throw err;            }

 

.net程式控制post資料 需登陸後保持session的方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.