响应未解析的HttpWebRequest和Set-Cookie标头(WP7)

我试图获取标题“Set-Cookie”或访问cookie容器,但Set-Cookie标头不可用。 cookie位于响应头中,但它不在客户端请求对象中。 我正在使用注册ClientHttp堆栈

 bool httpResult = WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp); 

这是回复:

 HTTP/1.1 200 OK Content-Type: application/xml; charset=utf-8 Connection: keep-alive Status: 200 X-Powered-By: Phusion Passenger (mod_rails/mod_rack) 3.0.0.pre4 ETag: "39030a9c5a45a24e485e4d2fb06c6389" Client-Version: 312, 105, 0, 0 X-Runtime: 44 Content-Length: 1232 Set-Cookie: _CWFServer_session=[This is the session data]; path=/; HttpOnly Cache-Control: private, max-age=0, must-revalidate Server: nginx/0.7.67 + Phusion Passenger 3.0.0.pre4 (mod_rails/mod_rack)   ...  

我的回调代码包含以下内容:

 var webRequest = (HttpWebRequest)result.AsyncState; raw = webRequest.EndGetResponse(result) as HttpWebResponse; foreach (Cookie c in webRequest.CookieContainer.GetCookies(webRequest.RequestUri)) { Console.WriteLine("Cookie['" + c.Name + "']: " + c.Value); } 

我也试过查看标题,但响应中也没有Set-Cookie标题。

关于可能出现什么问题的任何建议?

尝试显式传递新的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); 

您正在收到HttpOnly cookies:

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

出于安全原因,无法从代码访问这些cookie,但您仍可以在下次调用HttpWebRequest时使用它们。 更多相关内容: 从Windows Phone中的HttpWebResponse标题中读取HttpOnly Cookies

使用WP7.1,我在阅读非HttpOnly cookie时也遇到了问题。 我发现如果HttpWebRequest的响应来自缓存,它们就不可用。 使用随机数使查询唯一解决了缓存问题:

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

获得响应后,您可以从响应标头中获取cookie:

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

我从来没有设法让CookieContainer.GetCookies()方法起作用。

cookie是否为httponly? 如果是这样,您将无法看到它,但如果您为第二个请求使用相同的CookieContainer,则请求将包含cookie,即使您的程序无法看到它。

您必须直接编辑标题集合。 像这样的东西:

 request.Headers["Set-Cookie"] = "name=value"; request.BeginGetResponse(myCallback, request);