【问题标题】:How to handle status 302 redirect in c# httpwebreqest ASP.NET如何在 c# httpwebrequest ASP.NET 中处理状态 302 重定向
【发布时间】:2013-03-20 15:54:58
【问题描述】:

这是我的代码:

   @{
        //string postString = "parameter=value";
        const string contentType = "application/x-www-form-urlencoded";
        System.Net.ServicePointManager.Expect100Continue = false;

        CookieContainer cookies = new CookieContainer();
        HttpWebRequest webRequest = WebRequest.Create("http://somehost:8080/myApp") as HttpWebRequest;
        webRequest.Method = "POST";
        webRequest.AllowAutoRedirect = false;
        webRequest.ContentType = contentType;
        webRequest.CookieContainer = cookies;
        webRequest.ContentLength = postString.Length;
        webRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1";
        webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";

        StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
        requestWriter.Write(postString);
        requestWriter.Close();

        HttpWebResponse resp = webRequest.GetResponse() as HttpWebResponse;
        string location = resp.Headers["Location"];
        Response.Redirect(location);
    }

来自http://somehost:8080/myApp 的响应是 302 重定向到某个其他域。如果我使用 webRequest.AllowAutoRedirect = true; 并写入响应 (Response.Write(StreamReader(resp.GetResponseStream()).ReadToEnd())),则无法正确显示生成的 html,因为无法解析具有相关链接的资源。

所以,我想出了这个解决方案,但我觉得它不正确。在我看来,我的解决方案有点像“hackaround”。

有更好的解决方案吗?

【问题讨论】:

    标签: c# asp.net redirect httpwebrequest


    【解决方案1】:

    将您的相对网址更改为绝对网址

     url = objHttpWebResponse.Headers["Location"].ToString();
                            MessageBox.Show("Redirect To " + objHttpWebResponse.Headers["Location"]);
                            System.Threading.Thread.Sleep(2000);
                            Uri final = new Uri(new Uri(txtURL.Text), url);
                            string finalurl = final.AbsoluteUri;
                            download(finalurl);
    

    【讨论】:

      猜你喜欢
      • 2021-09-13
      • 2020-03-16
      • 1970-01-01
      • 1970-01-01
      • 2018-04-18
      • 1970-01-01
      • 2012-06-25
      • 2018-09-28
      相关资源
      最近更新 更多