复制HTTP请求的InputStream [英] Copying Http Request InputStream

查看:290
本文介绍了复制HTTP请求的InputStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实施转发该传入Web请求,并将其转发到另一个网页的代理操作方法,增加了一些头。操作方法适用于GET请求文件,但我仍然转发传入POST请求挣扎。

I'm implementing a proxy action method that forwards the incoming web request and forwards it to another web page, adding a few headers. The action method works file for GET requests, but I'm still struggling with forwarding the incoming POST request.

问题是,我不知道如何将请求主体正确写入传出的HTTP请求流。

The problem is that I don't know how to properly write the request body to the outgoing HTTP request stream.

下面是一个什么样我到目前为止已经有了一个缩短的版本:

Here's a shortened version of what I've got so far:

//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请求时,我得到了以下异常:

As soon as I call GetResponse on the outgoing http request, I get the following exception:

ProtocolViolationException: You must write ContentLength bytes to the request stream before calling [Begin]GetResponse.

我不明白为什么会这样,因为requestStream.CopyTo应该采取写字节适量的照顾。

I don't understand why this is happening, since requestStream.CopyTo should have taken care of writing the right amount of bytes.

任何建议将是极大的AP preciated。

Any suggestions would be greatly appreciated.

谢谢,

阿德里安

推荐答案

是,.NET是对此非常挑剔。解决问题的方法是既冲洗 关闭该流。换句话说:

Yes, .Net is very finicky about this. The way to solve the problem is to both flush and close the stream. In other words:

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())
{
    ...
}

这篇关于复制HTTP请求的InputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆