HttpWebRequest not redirecting automatically

13 Views Asked by At

I am having issues with my code not doing a redirect. When I set AllowAutoREdirect to FALSE I get a link to click on that will redirect me to the new urL and also give me a message about cookies being required. When I set AllowAutoRedirect to TRUE it just appends the new url info to the page that I am already on. Here is my code

            var data = Encoding.ASCII.GetBytes(flds.ToString());          
        string url = "https://checkout.globalgatewaye4.firstdata.com/payment";
        string userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36";

        ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;          

        //begin HttpWebRequest
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
        webRequest.ContentType = "application/x-www-form-urlencoded";
        webRequest.AllowAutoRedirect = true;
        
        webRequest.Method = "POST";          
        webRequest.ContentLength = data.Length;          
        webRequest.Headers.Add("Accept-Language: ru-RU, en; q = 0.5");          
       
        webRequest.UserAgent = userAgent;

        using (var stream = webRequest.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);

        }

                 
        try
        {
            var rsp = webRequest.GetResponse();
            Console.WriteLine(rsp.Headers["Location"]);
            response_label.Text = new StreamReader(rsp.GetResponseStream()).ReadToEnd();
           
        }
        catch (WebException e)
        {
            var rsp = (HttpWebResponse)e.Response;
            if (rsp.StatusCode == HttpStatusCode.Moved ||
                rsp.StatusCode == HttpStatusCode.MovedPermanently ||
                rsp.StatusCode == HttpStatusCode.Found)
            {
                Console.WriteLine(rsp.Headers["Location"]);
            }
            else throw;

        }
0

There are 0 best solutions below