HttpWebRequest and Set-Cookie header in response not parsed (WP7)

两盒软妹~` 提交于 2019-11-30 21:36:55

Try explicitly passing a new CookieContainer:

CookieContainer container = new CookieContainer();
container.Add(new Uri("http://yoursite"), new Cookie("name", "value"));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://yoursite");
request.CookieContainer = container;
request.BeginGetResponse(new AsyncCallback(GetData), request);
Berthier Lemieux

You are receiving HttpOnly cookies:

Set-Cookie: _CWFServer_session=[This is the session data]; path=/; HttpOnly 

For security reasons, those cookies can't be accessed from code, but you still can use them in your next calls to HttpWebRequest. More on this here : Reading HttpOnly Cookies from Headers of HttpWebResponse in Windows Phone

With WP7.1, I also had problems reading non HttpOnly cookies. I found out that they are not available if the response of the HttpWebRequest comes from the cache. Making the query unique with a random number solved the cache problem :

// The Request
Random random = new Random();  
// UniqueQuery is used to defeat the cache system that destroys the cookie.
_uniqueQuery = "http://my-site.somewhere?someparameters=XXX"
       + ";test="+ random.Next();

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_uniqueQuery);
request.BeginGetResponse(Response_Completed, request);

Once you get the response, you can fetch the cookie from the response headers:

void Response_Completed(IAsyncResult result)
{
    HttpWebRequest request = (HttpWebRequest)result.AsyncState;
    HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
    String header = response.Headers["Set-Cookie"]; 

I never managed to get the CookieContainer.GetCookies() method to work.

Is the cookie httponly? If so, you won't be able to see it, but if you use the same CookieContainer for your second request, the request will contain the cookie, even though your program won't be able to see it.

You must edit the headers collection directly. Something like this:

request.Headers["Set-Cookie"] = "name=value";

request.BeginGetResponse(myCallback, request);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!