从httpwebresponse位置标头重定向到URL

时间:2016-05-31 08:57:43

标签: c# asp.net http-post http-status-codes

我试图重定向我的ASP.NET页面加载以重定向到另一个页面,其URL将来自HTTP帖子的响应。

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

此响应重定向以404错误结束。请帮忙

2 个答案:

答案 0 :(得分:1)

在下面的代码行中:

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

Response.Redirect(returnURL);

如果returnURL不等于httpStatusCode,则HttpStatusCode.Found变量可能为空。您可能希望为其他状态代码传递不同的有效URL。

答案 1 :(得分:0)

使用

System.Threading.Thread.Sleep(2000);

Response.Redirect(returnURL);