我正在實現一種代理操作方法,該方法將傳入的Web請求轉發並轉發給另一個網頁,並添加一些標頭。操作方法爲GET請求工作文件,但我仍然努力轉發傳入的POST請求。複製Http請求InputStream
問題是我不知道如何正確地將請求正文寫入傳出的HTTP請求流。
這裏是我到目前爲止已經有一個縮短版:
//the incoming request stream
var requestStream=HttpContext.Current.Request.InputStream;
//the outgoing web request
var webRequest = (HttpWebRequest)WebRequest.Create(url);
...
//copy incoming request body to outgoing request
if (requestStream != null && requestStream.Length>0)
{
long length = requestStream.Length;
webRequest.ContentLength = length;
requestStream.CopyTo(webRequest.GetRequestStream())
}
//THE NEXT LINE THROWS A ProtocolViolationException
using (HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse())
{
...
}
當我打電話的GetResponse對即將離任的HTTP請求,我得到以下異常:
ProtocolViolationException: You must write ContentLength bytes to the request stream before calling [Begin]GetResponse.
我不明白爲什麼會發生這種情況,因爲requestStream.CopyTo應該注意寫入正確的字節數。
任何建議,將不勝感激。
感謝,
阿德里安
相關問題 - http://stackoverflow.com/questions/226784/how-to-create-a-simple-proxy-in-c – 2010-08-10 09:55:17
@詹姆斯曼寧:感謝您的鏈接,但我已經過去了。我的代理適用於各種GET請求。這只是POST請求正文仍然給我的問題。 – 2010-08-10 10:19:54
在繼續調用webRequest.GetResponse()之前,您是否嘗試過在webRequest.GetRequestStream()返回的流上調用Stream.Flush()? – 2010-08-10 11:41:36