2016-11-30 62 views
0

我正在使用我的c#應用向網頁發送請求。在發送任何請求之前,我必須登錄此網頁。每次我想要做一些工作時,我都希望避免記錄,所以我在VARBINARY列中將cookie存儲在sql server數據庫中。我必須每次更新每個cookie嗎?

比方說,我送50 POST requests每天:

private string getRequest(string url, string postData = "") 
     { 
      try 
      { 
       System.Net.ServicePointManager.Expect100Continue = true; 
       StreamReader reader; 
       var request = WebRequest.Create(url) as HttpWebRequest; 
       request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14"; 
       request.CookieContainer = Cookie; 
       request.AllowAutoRedirect = true; 
       request.ContentType = "application/x-www-form-urlencoded"; 
       request.Headers.Add("X-Requested-With", "XMLHttpRequest"); 
       postData = Uri.EscapeUriString(postData); 
       request.Method = "POST"; 
       request.ContentLength = postData.Length; 
       Stream requestStream = request.GetRequestStream(); 
       Byte[] postBytes = Encoding.ASCII.GetBytes(postData); 

       requestStream.Write(postBytes, 0, postBytes.Length); 
       requestStream.Close(); 

       HttpWebResponse response = request.GetResponse() as HttpWebResponse; 
       foreach (Cookie tempCookie in response.Cookies) 
       { 
        Cookie.Add(tempCookie); 
       } 
       reader = new StreamReader(response.GetResponseStream()); 
       string readerReadToEnd = reader.ReadToEnd(); 
       response.Close(); 

       database.updateCookie(AccountId, Cookie); //here I am updating the cookies 

       return readerReadToEnd; 
      } 
      catch { return ""; } 

我真的需要每個請求後更新Cookies?或者,也許我可以在發送50 POST requests後只更新我的cookie一次?

我在問,因爲有時我的餅乾會持續幾天,有時他們會在1分鐘後死亡。我不知道爲什麼以及如何避免這種情況。

我需要儲存最新的曲奇嗎?或者我可以每次都使用相同的曲奇嗎?

+0

這取決於服務器發送的cookie。 – SLaks

+0

爲什麼你需要在你的數據庫中存儲cookies?如果你把它們存儲在數據庫中,Cookies也屬於客戶端機器,客戶端機器上存儲的是什麼? –

+0

@SeanLange因爲我有時會重啓我的電腦。我想在數據庫中存儲cookie以避免日誌記錄。 – Dawvawd

回答

0

每個網站決定特定cookie的有效期限。因此,您需要分別爲每個網站獲取該信息才能正確執行此操作。注意cookie上的「過期」(在「響應的set-cookie」標題中)可能會爲您提供有關cookie何時保證到期的初步指導。

常見到期/有效期範圍:

  • 身份驗證cookie - 10分鐘至1天
  • ASP.Net會話狀態 - 由20分鐘
  • CSRF保護 - 可能更新每個響應
+0

嗯,但如果我輸入例如Stackoverflow 7天后,我仍然記錄。我想在我的C#應用​​程序中做同樣的事情。如果我發送另一個請求例如3天后,我想已經登錄在我的C#應用​​程序。 – Dawvawd

+0

@Dawvawd「common」!=「every one one」...隨時瞭解具體網站如何處理身份驗證和破解...請注意,某些網站提供了適當的API以訪問來自非網絡應用程序的信息 - 具體取決於你的目標網站可能是更好的方法,而不是希望在抓取時獲得正確的cookies。 –

相關問題