Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reverse proxy in mvc

I have to implement something like proxy in mvc to send 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 in this solution i first download file and then send downloded file to user with is not what i want. I want to send file to user as soon as I start to download it like in this Online Anonymizer for example http://bind2.com/

Any suggestions how to achieve this?

like image 562
user656822 Avatar asked Mar 13 '11 19:03

user656822


1 Answers

The following line in the above sample:

res.Write(reader.ReadToEnd());

Is equivalent to:

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

I.e. the entire web response is being downloaded and stored in a string before it is being passed 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 copying code taken from Best way to copy between two Stream instances - C#)

This copies the stream in 32 KB chunks - you may want to make this chunk size smaller.

like image 139
Justin Avatar answered Sep 30 '22 00:09

Justin