gpt4 book ai didi

c# - HttpWebResponse.Cookies 为空,尽管有 Set-Cookie header (无重定向)

转载 作者:IT王子 更新时间:2023-10-29 04:23:33 27 4
gpt4 key购买 nike

我正在努力弄清楚这里出了什么问题。我正在发送登录信息,我可以在 header 中看到具有正确值的 Set-Cookie,但 Cookies 集合未被填充。

这是 HTTPS,登录自动重定向,但我使用 AllowAutoRedirect=false 禁用它以尝试解决此问题。

在此屏幕截图中,您可以轻松地看到调试信息并且应该设置 cookie。我正在将我的 httpWebRequest.Cookie 设置为新的 CookieCollection。

Right click and select view image to see full-size.

HttpWebRequest httpRequest;
CookieContainer reqCookies = new CookieContainer();
string url = "https://example.com";
string[] email = user.Split('@');
email[0] = System.Web.HttpUtility.UrlEncode(email[0]);
user = email[0] + "@" + email[1];
pass = System.Web.HttpUtility.UrlEncode(pass);

string postData = "email=" + user + "&password=" + pass;
byte[] byteData = Encoding.UTF8.GetBytes(postData);

httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.Referer = url;
httpRequest.CookieContainer = reqCookies;
httpRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1003.1 Safari/535.19";
httpRequest.Accept = "text/html, application/xhtml+xml, */*";
httpRequest.ContentType = "application/x-www-form-urlencoded";
httpRequest.ContentLength = byteData.Length;
using (Stream postStream = httpRequest.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
postStream.Close();
}

httpRequest.AllowAutoRedirect = false;
HttpWebResponse b = (HttpWebResponse)httpRequest.GetResponse();

尝试使用完全相同的代码连接到 http://www.yahoo.com cookies 被放入我的收藏中......啊......

这是 Set-Cookie header 值:

s=541E2101-B768-45C8-B814-34A00525E50F; Domain=example.com; Path=/; Version=1

最佳答案

更新 五年后,实际上有人提到了正确的做法:首先正确设置 CookieContainer 并让它处理所有事情。请进一步引用 Sam 的解决方案。

在阅读由 C# ASP.NET 应用程序创建的 C# 中的 Cookie 时,我也发现了这个问题...;)

不确定是否与它有关,但我发现在我的案例中设置的两个 Cookie 是写在一个 Set-Cookie header 中的,cookie 有效负载用逗号分隔。因此,我采用了 AppDeveloper 的解决方案来处理这个多 cookie 问题,并修复了我在评论中提到的名称/值问题。

private static void fixCookies(HttpWebRequest request, HttpWebResponse response) 
{
for (int i = 0; i < response.Headers.Count; i++)
{
string name = response.Headers.GetKey(i);
if (name != "Set-Cookie")
continue;
string value = response.Headers.Get(i);
foreach (var singleCookie in value.Split(','))
{
Match match = Regex.Match(singleCookie, "(.+?)=(.+?);");
if (match.Captures.Count == 0)
continue;
response.Cookies.Add(
new Cookie(
match.Groups[1].ToString(),
match.Groups[2].ToString(),
"/",
request.Host.Split(':')[0]));
}
}
}

关于c# - HttpWebResponse.Cookies 为空,尽管有 Set-Cookie header (无重定向),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15103513/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com