Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Writing responseStream to context.response.outputstream

Tags:

c#

asp.net

Our ASP.net app needs to relay some requests to another server, get the data and serve it. We can download the data to a file and serve it or directly serve the response stream from origin server to client. Data includes js/css/images/font files/mp3 etc.

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();

How can I directly pass newResponse.GetResponseStream() to context.Response.OutputStream.

like image 419
adnan kamili Avatar asked Sep 19 '25 21:09

adnan kamili


1 Answers

You can't pass the stream directly, but you can conveniently write one to the other (which will create a read/write-loop internally):

sourceStream.CopyTo(destinationStream);
like image 50
Marc Gravell Avatar answered Sep 21 '25 10:09

Marc Gravell