Skip to main content
 首页 » 编程设计

c#之HttpWebRequest resp.Headers ["Set-Cookie"] 为空

2024年02月02日28daizhj

更新 1: 发布/获取标题的屏幕截图:http://imageshack.us/photo/my-images/826/getpost.png

我正在寻求有关网络请求的帮助。请求的目的是登录站点并检索 Set-Cookie header 。我很感激任何帮助!

我正在尝试使用以下代码登录网站并检索 cookie 值。但是,Set-Cookie header 始终为空:

static void Main(string[] args) 
{ 
    string formUrl = "https://account.guildwars2.com/login"; 
    string formParams = string.Format("email={0}&password={1}", "xxx", "xxx"); 
    string cookieHeader; 
    var req = (HttpWebRequest)WebRequest.Create(formUrl); 
    req.Referer = "https://account.guildwars2.com/login"; 
    req.ContentType = "application/x-www-form-urlencoded"; 
    req.Method = "POST"; 
    req.KeepAlive = true; 
    byte[] bytes = Encoding.ASCII.GetBytes(formParams); 
    req.ContentLength = bytes.Length; 
    using (Stream os = req.GetRequestStream()) 
    { 
        os.Write(bytes, 0, bytes.Length); 
    } 
    WebResponse resp = req.GetResponse(); 
    cookieHeader = resp.Headers["Set-Cookie"]; 
} 

我不确定这是否与重定向有关,因为在 C# 应用程序中,response-uri 是“https://account.guildwars2.com/login?redirect_uri=/download”

响应 header Chrome

  • 内容长度:0
  • 内容类型:文本/html
  • 日期:2012 年 9 月 29 日星期六 15:07:30 GMT
  • 位置:下载
  • 服务器:Microsoft-IIS/7.5
  • 设置 Cookie:s=60B845F0-4E22-4A4B-890B-F3B885CEF9AE;域名=guildwars2.com;路径=/;版本=1
  • X-Powered-By:ARR/2.5

来自 C# 应用程序的响应

  • 内容长度:7344
  • 内容类型:文本/html
  • 日期:2012 年 9 月 29 日星期六 15:42:44 GMT
  • 服务器:Microsoft-IIS/7.5
  • X-Powered-By:ARR/2.5

请您参考如下方法:

默认情况下,HttpWebRequest 自动遵循 HTTP 重定向响应,这会阻止您捕获原始响应中的 Set-Cookie header 。要禁用此行为,请设置 AllowAutoRedirect在发送请求之前设置为 false:

req.AllowAutoRedirect = false;