简体   繁体   English

从httpwebresponse位置标头重定向到URL

[英]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. 我正在尝试将其上的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);

This response redirect ends in 404 error. 此响应重定向以404错误结束。 Please help 请帮忙

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 . 所述returnURL如果变量可以是空的httpStatusCode不等于HttpStatusCode.Found You might want to pass a different valid URL for other status codes. 您可能希望为其他状态代码传递一个不同的有效URL。

Use 采用

System.Threading.Thread.Sleep(2000);

before 之前

Response.Redirect(returnURL);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM