0

有时,我的程序似乎无法创建 HTTP Post。我把它缩小到一个显然丢失的cookie。

一些调查,我缩小了范围

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);
    }
}

我想了解的是为什么 GetResponse 调用会删除 cookie。在 Fiddler 中检查,没有提到这个 cookie。唯一的 cookie 代码是设置两个 cookie。一个已经存在,一个不存在。

cookie 肯定没有过期。我对此完全不知所措

干杯

4

1 回答 1

1

尝试使用这样的 CookieCollection 和 CookieContainer 来维护您的 cookie:

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
于 2013-09-26T15:15:22.273 回答