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

走远了吗. 提交于 2020-02-23 00:42:54

问题


pretty much...i want to do something like this:

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

Is this possible?


回答1:


No, but you can of course copy the data, either synchronously or asynchronously.

  • Allocate a buffer (like 4kb in size or so)
  • Do a read, which will either return the number of bytes read or 0 if the end of the stream has been reached
  • 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);
    }
}



回答2:


This answer has a method CopyStream to copy data between streams (and also indicates the built-in way to do it in .NET 4).

You could do something like:

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


来源:https://stackoverflow.com/questions/2790750/how-do-i-use-c-sharp-and-asp-net-to-proxy-a-webrequest

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!