【问题标题】:response.Cookies is always empty (length: 0)response.Cookies 始终为空(长度:0)
【发布时间】:2026-01-18 09:35:01
【问题描述】:

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

我正在制作一个程序来管理我在一个小型社区网站上的帐户。 我能够发出获取和发布请求(成功登录等),但我无法维护会话 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? 提前谢谢

【问题讨论】:

  • 您是否真的在某个时候向 CookieCollection 添加了 cookie?
  • 是的,我用上一个请求中的那个覆盖了 cookiecollection。问题是我在请求时没有收到来自服务器的 cookie

标签: c# cookies httpwebrequest


【解决方案1】:

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

考虑到上述情况,服务器似乎没有添加额外的 cookie,这就是为什么您在响应中没有收到任何 cookie。那有意义吗 ?

【讨论】:

  • 这完全有道理,让我感到羞耻。成功了,非常感谢