C# - Writing responseStream to context.response.outputstream

本文关键字:context response outputstream to responseStream Writing | 更新日期: 2023-09-27 18:03:27

我们的ASP.net应用程序需要将一些请求转发到另一台服务器,获取数据并提供服务。我们可以将数据下载到文件中并提供服务,或者直接提供从源服务器到客户端的响应流。数据包括js/css/images/font文件/mp3等

HttpWebRequest forwardRequest = (HttpWebRequest)WebRequest.Create(remoteUrl);
                forwardRequest.ContentType = context.Request.ContentType;
                forwardRequest.UserAgent = context.Request.UserAgent;
                forwardRequest.Method = context.Request.HttpMethod;
                //add post check
                HttpWebResponse newResponse = (HttpWebResponse)forwardRequest.GetResponse();
                MemoryStream ms = new MemoryStream();
                newResponse.GetResponseStream().CopyTo(ms);
                context.Response.ContentType = newResponse.ContentType;
                context.Response.StatusCode = 200;
                context.Response.BinaryWrite(ms.GetBuffer());
                ms.Close();
                context.Response.Flush();
                context.Response.Close();
                context.Response.End();

如何将newResponse.GetResponseStream()直接传递给context.Response.OutputStream

C# - Writing responseStream to context.response.outputstream

不能直接传递流,但可以方便地将一个流写入另一个流(这会在内部创建一个读/写循环):

sourceStream.CopyTo(destinationStream);