c# - response.Cookies 始终为空(长度为 : 0)

标签 c# cookies httpwebrequest

我在使用 HttpWebRequest 时遇到了处理 cookie 的问题。

我正在制作一个程序来管理我在一个小型社区网站上的帐户。 我能够发出获取和发布请求(成功登录等),但我无法维护 session cookie 以保持登录状态。

我的代码是这样的:

this.cookies = new CookieCollection();
request = (HttpWebRequest)WebRequest.Create(requestURL);
request.CookieContainer = new CookieContainer();
...
request.CookieContainer.Add(cookies);
ASCIIEncoding encodage = new System.Text.ASCIIEncoding();
byte[] data = encodage.GetBytes(Post);
request.AllowAutoRedirect = true;
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = "whatever";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.Method = "POST";
request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.AllowWriteStreamBuffering = true;
request.ContentLength = data.Length;
newStream = request.GetRequestStream();
request.ProtocolVersion = HttpVersion.Version11;
newStream.Write(data, 0, data.Length);
...
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
this.cookies = response.Cookies;
...

response.Cookies 总是空的(长度:0)而且它不应该。 谁能告诉我我做错了什么?为什么没有与响应关联的 cookie? 提前致谢

最佳答案

只需从 Request.Cookies 集合中读取它。 Response.Cookies 中只有服务器端添加的新 cookie 可用。 Request.Cookies 包含所有(请求+响应)Cookie。

考虑到上面的内容,服务器似乎没有添加额外的 cookie,这就是为什么您在响应中没有收到 cookie 的原因。那有意义吗 ?

关于c# - response.Cookies 始终为空(长度为 : 0) ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11527061/

相关文章:

c# - 垃圾收集期间缓冲区溢出 : psychic debugging request

c# - 以类似于 wpf 控件错误的方式显示警告

javascript - 使用 showdowbox.js 弹出窗口的 18+ 免责声明

c# - 在 C# 中通过 POST 发送 JSON 并接收返回的 JSON?

python - python 中的 HTTP 请求超时

c# - Epplus 行和列中的最后一个单元格 - C#

c# - 网络核心 : Override WebApplicationFactory Services DbContext with InMemory Database

java - 在 Java 中读取安全 session cookie

java - 如何在 Apache HttpClient 4.1 中处理 session

cocoa-touch - 如何在IOS中进行基本的http