Search code examples
c#http-redirectrequestheaderhttpwebrequest

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


I'm making a tool to check a login on a website, AllowAutoRedirect = false crashes the program with a 302, Sending all the headers and cookies and payload goes fine on AllowAutoRedirect = true goes fine but I need to gather the cookies from the domain before the redirect.

How to? Thanks.

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();

Solution

  • Adding a try catch block solves this issue, inside the catch you can get the response from the server and be able to handle the response there.

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