Raju
Raju

Reputation: 207

Redirect to an URL from httpwebresponse Location header

Im trying to redirect my ASP.NET page on it load to redirect to another page, whose URL i would get from the response of an HTTP post.

HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);

StringBuilder postData = new StringBuilder();
postData.Append("xmldata=" + HttpUtility.UrlEncode(xdoc));
postData.Append("&signature=" +HttpUtility.UrlEncode(signature));
httpWebRequest.Method = "POST";
httpWebRequest.Accept = "*/*";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
using (Stream requestStream = httpWebRequest.GetRequestStream())
{
    using (MemoryStream ms = new MemoryStream())
    {
        using (BinaryWriter bw = new BinaryWriter(ms))
        {
            bw.Write(Encoding.UTF8.GetBytes(postData.ToString()));
            ms.WriteTo(requestStream);
        }
    }
}
httpWebRequest.AllowAutoRedirect = false;
var returnURL="";
using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
    httpStatusCode = httpWebResponse.StatusCode;
     if (httpStatusCode == HttpStatusCode.Found)
     {
        returnURL= httpWebResponse.Headers["Location"].ToString();
     }
}

Response.Redirect(returnURL);

This response redirect ends in 404 error. Please help

Upvotes: 0

Views: 7671

Answers (2)

d.i.joe
d.i.joe

Reputation: 709

In the below lines of code:

var returnURL="";
using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
    httpStatusCode = httpWebResponse.StatusCode;
     if (httpStatusCode == HttpStatusCode.Found)
     {
        returnURL= httpWebResponse.Headers["Location"].ToString();
     }
}

Response.Redirect(returnURL);

The returnURL variable may be empty if the httpStatusCode is not equal to HttpStatusCode.Found. You might want to pass a different valid URL for other status codes.

Upvotes: 1

user6403036
user6403036

Reputation:

Use

System.Threading.Thread.Sleep(2000);

before

Response.Redirect(returnURL);

Upvotes: 0

Related Questions