Reverse proxy in mvc

I need to implement something like a proxy in mvc to send a user file that is on another server. I found this class:

public class ProxyHandler : IHttpHandler, IRouteHandler { public bool IsReusable { get { return true; } } public void ProcessRequest(HttpContext context) { string str = "http://download.thinkbroadband.com/100MB.zip"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(str); request.Method = "GET"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream()); HttpResponse res = context.Response; res.Write(reader.ReadToEnd()); } public IHttpHandler GetHttpHandler(RequestContext requestContext) { return this; } } 

The problem is that in this solution, I first upload the file and then send the downstream file to the user, but that is not what I want. I want to send the file to the user as soon as I start uploading it, for example, in this online anonymizer http://bind2.com/

Any suggestions to achieve this?

+7
source share
1 answer

The following line in the example above:

 res.Write(reader.ReadToEnd()); 

It is equivalent to:

 string responseString = reader.ReadToEnd(); res.Write(responseString); 

those. the entire web response is downloaded and stored in the line before it is sent to the client.

Instead, you should use something like the following:

 Stream responseStream = response.GetResponseStream(); byte[] buffer = new byte[32768]; while (true) { int read = responseStream.Read(buffer, 0, buffer.Length); if (read <= 0) return; context.Response.OutputStream.Write(buffer, 0, read); } 

(Stream copy code taken from Best way to copy between two Stream instances - C # )

This copies the stream in 32 KB blocks - you might want to reduce the size of this fragment.

+8
source

All Articles