【发布时间】:2011-03-27 17:31:52
【问题描述】:
我正在实现一个代理操作方法,该方法转发传入的 Web 请求并将其转发到另一个网页,并添加一些标头。 action 方法适用于 GET 请求的文件,但我仍在努力转发传入的 POST 请求。
问题是我不知道如何正确地将请求正文写入传出的 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())
{
...
}
当我对传出的 http 请求调用 GetResponse 时,我会收到以下异常:
ProtocolViolationException: You must write ContentLength bytes to the request stream before calling [Begin]GetResponse.
我不明白为什么会这样,因为 requestStream.CopyTo 应该负责写入正确数量的字节。
任何建议将不胜感激。
谢谢,
阿德里安
【问题讨论】:
-
@James Manning:感谢您的链接,但我已经完成了。我的代理适用于各种 GET 请求。只是 POST 请求正文仍然给我带来问题。
-
在继续调用 webRequest.GetResponse() 之前,您是否尝试过在 webRequest.GetRequestStream() 返回的流上调用 Stream.Flush()?
-
@Mattias S:我刚做了,但似乎没有任何区别。
-
出于调试的目的,我可能会将其更改为将流写入中间字节数组(memorystream,然后是 toarray),检查其内容和长度,然后写入字节数组。另外,恕我直言,您应该使用 using 将 webRequest.GetRequestStream() 分配给本地 var,因此您在写入之前关闭请求流,因此类似于 using (var rs = webRequest.GetRequestStream()) { requestStream.CopyTo( rs); } (或字节数组,如果你走那条路)。一旦我应该在我应该处理流的时候(并且刷新/关闭发生),我已经有很多错误消失了
标签: c# asp.net asp.net-mvc httpwebrequest webrequest