POST 请求重定向,但是 AllowAutoRedirects = false 给出 302 异常,如何避免?

POST requests redirects, but AllowAutoRedirects = false gives 302 exception, how to avoid it?

我正在制作一个工具来检查网站上的登录,AllowAutoRedirect = false 使程序崩溃并返回 302, 在 AllowAutoRedirect = true 上发送所有 headers 和 cookies 和有效载荷都很好,但我需要在重定向之前从域中收集 cookies。

怎么办?谢谢

var request = (HttpWebRequest)WebRequest.Create(url);

payload
requestheaders

using (var stream = request.GetRequestStream())
{
      stream.Write(data, 0, data.Length);
      stream.Close();
}

request.AllowAutoRedirect = false; <-- crashes here (302 Found Exception)


var response = (HttpWebResponse)request.GetResponse();

添加一个 try catch 块解决了这个问题,在 catch 中您可以从服务器获取响应并能够在那里处理响应。

try
{
     //All your request code here...
     var response = (HttpWebResponse)request.GetResponse();
     
}
catch (WebException ex)
{
     var response = ex.Response as HttpWebResponse;   
     //handle the request here
}