2013-03-20 63 views
1

這裏是我的代碼:如何處理狀態302重定向在C#httpwebreqest ASP.NET

@{ 
     //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'。

有更好的解決方案嗎?

回答

0

改變你的相對URL爲絕對

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); 
相關問題