复制Http Request InputStream

Adr*_*ore 6 c# asp.net asp.net-mvc webrequest httpwebrequest

我正在实现一个代理操作方法,该方法转发传入的Web请求并将其转发到另一个网页,添加一些标头.动作方法为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())
                {
                    ...
                }
Run Code Online (Sandbox Code Playgroud)

一旦我在传出的http请求上调用GetResponse,我就会收到以下异常:

ProtocolViolationException: You must write ContentLength bytes to the request stream before calling [Begin]GetResponse.
Run Code Online (Sandbox Code Playgroud)

我不明白为什么会发生这种情况,因为requestStream.CopyTo应该负责编写正确数量的字节.

任何建议将不胜感激.

谢谢,

阿德里安

Bri*_*ian 13

是的,.Net非常挑剔.解决问题的方法是刷新关闭流.换一种说法:

Stream webStream = null;

try
{
    //copy incoming request body to outgoing request
    if (requestStream != null && requestStream.Length>0)
    {
        long length = requestStream.Length;
        webRequest.ContentLength = length;
        webStream = webRequest.GetRequestStream();
        requestStream.CopyTo(webStream);
    }
}
finally
{
    if (null != webStream)
    {
        webStream.Flush();
        webStream.Close();    // might need additional exception handling here
    }
}

// No more ProtocolViolationException!
using (HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse())
{
    ...
}
Run Code Online (Sandbox Code Playgroud)