tags:

views:

228

answers:

1

Hello... My proxy usage : "Proxy.ashx?url="

Code:

<%@ WebHandler Language="C#" Class="Proxy" %>

public class Proxy : IHttpHandler {

public void ProcessRequest (HttpContext context) {

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(context.Request["url"]);
    request.UserAgent = context.Request.UserAgent;
    request.ContentType = context.Request.ContentType;
    request.Method = context.Request.HttpMethod;

    byte[] trans = new byte[1024];
    int offset = 0;
    int offcnt = 0;

    if (request.Method.ToUpper() == "POST")
    {
        Stream nstream = request.GetRequestStream();
        while (offset < context.Request.ContentLength)
        {
            offcnt = context.Request.InputStream.Read(trans, offset, 1024);
            if (offcnt > 0)
            {
                nstream.Write(trans, 0, offcnt);
                offset += offcnt;
            }
        }
        nstream.Close();
    }

    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
        context.Response.ContentType = response.ContentType;

        using (Stream receiveStream = response.GetResponseStream())
        {
            offset = 0;
            offcnt = receiveStream.Read(trans, offset, 1024);
            while (offcnt>0)
            {
                context.Response.OutputStream.Write(trans, 0, offcnt);
                offset += offcnt;
                if (offcnt >= 0)
                {
                    try
                    {
                        offcnt = receiveStream.Read(trans, offset, 1024);
                    }
                    catch (Exception)
                    {
                        break;
                    }
                }
                else
                    break;       
            }
        }
        context.Response.OutputStream.Close();
        context.Response.Flush();
        response.Close();
    }
}

public bool IsReusable {
    get {
        return false;
    }
}

}

I always get a blank page as result (Proxy.ashx?url=http://www.google.com) ... Any idea what mistake I´ve done?

+1  A: 

For the POST handling, ContentLength may be 0, don't rely on it. Just open the stream and read as much as you can until the stream returns no more data.

For the rest, the offset when reading into the array must remain 0, since it is the offset of the array and not of the stream.

using (Stream receiveStream = response.GetResponseStream()) {
   for (int offcnt = receiveStream.Read(trans, 0, trans.Length); offcnt > 0; offcnt = receiveStream.Read(trans, 0, trans.Length)) {
      context.Response.OutputStream.Write(trans, 0, offcnt);
   }
}
Lucero
Thanks!"For the rest, the offset when reading into the array must remain 0, since it is the offset of the array and not of the stream."What do you suggest to fix that problem?
Paul
Thanks! That worked great!
Paul