简体   繁体   English

如何使用C#和ASP.net代理WebRequest?

[英]How do I use C# and ASP.net to proxy a WebRequest?

pretty much...i want to do something like this: 差不多......我想做这样的事情:

Stream Answer = WebResp.GetResponseStream();
Response.OutputStream = Answer;

Is this possible? 这可能吗?

No, but you can of course copy the data, either synchronously or asynchronously. 不,但您当然可以同步或异步复制数据。

  • Allocate a buffer (like 4kb in size or so) 分配一个缓冲区(大小约为4kb)
  • Do a read, which will either return the number of bytes read or 0 if the end of the stream has been reached 执行读操作,该读操作将返回读取的字节数,如果已到达流的末尾,则返回0
  • If data was received, write the amount read and loop to the read 如果收到数据,则将读取的数量写入并循环读取

Like so: 像这样:

using (Stream answer = webResp.GetResponseStream()) {
    byte[] buffer = new byte[4096];
    for (int read = answer.Read(buffer, 0, buffer.Length); read > 0; read = answer.Read(buffer, 0, buffer.Length)) {
        Response.OutputStream.Write(buffer, 0, read);
    }
}

This answer has a method CopyStream to copy data between streams (and also indicates the built-in way to do it in .NET 4). 这个答案有一个方法CopyStream来在流之间复制数据(并且还指示了在.NET 4中执行它的内置方法)。

You could do something like: 你可以这样做:

using (stream answer = WebResp.GetResponseStream())
{
    CopyStream(answer, Response.OutputStream); 
    Response.Flush();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM