2013-07-31 139 views
0

偶爾,我的程序似乎無法制作HTTP Post。我把它縮小到一個餅乾,顯然正在丟失。Cookie在HttpWebRequest上丟失/丟失GetReponse

一些調查,我把範圍縮小

HttpWebResponse response = (HttpWebResponse)http.GetResponse(); 

奇怪的是,它不發生的時間,通常當此方法是第一次運行,那麼一切都很好(我強迫重新後除了此cookie。

我似乎已經入侵了一個解決方案一起,對於這種情況下的工作(但我擔心它會破壞其他情況下,如通常與黑客的解決方案的方式)。

var cookiesPrePull = cookies.GetCookies(http.RequestUri); 
HttpWebResponse response = (HttpWebResponse)http.GetResponse(); 
foreach (Cookie cookiePre in cookiesPrePull) 
{ 
    bool bExist = false; 
    foreach (Cookie cookiePost in cookies.GetCookies(http.RequestUri)) 
    { 
     if (cookiePre.Name == cookiePost.Name) 
     { 
      bExist = true; 
      break; 
     } 
    } 
    if (!bExist) 
    { 
     cookies.Add(cookiePre); 
    } 
} 

我想了解的是爲什麼Cookie被GetResponse調用所拋棄。審查小提琴手,沒有提到這個cookie。唯一的cookie代碼是設置兩個cookie。一個已經存在,一個不存在。

該cookie肯定沒有過期。在我在這個

歡呼使用CookieCollection和的CookieContainer這樣保持你的cookies

回答

1

嘗試完全喪失:

CookieContainer container = new CookieContainer(); 
CookieCollection cookies = new CookieCollection(); 

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://somesite.com/login"); 
request.CookieContainer = container; 

HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
cookies = response.Cookies; // capture the cookies from the response 

request = (HttpWebRequest)WebRequest.Create("http://somesite.com/profile"); 
request.CookieContainer = container; 
request.CookieContainer.Add(cookies); // add cookies from the previous response to the new request 

response = (HttpWebResponse)request.GetResponse(); 
cookies = response.Cookies; // capture the cookies from the response