Example of Proxying Binary Data With ASP.NET
Recently I was working on a project and needed to proxy a request to a website that was returning a binary file. I ran into some problems with my first pass at a solution. I believe the problem was a consequence of proxying binary data without getting at the underlying streams. I’m not sure how often I’ll need to do this, but I thought it might be useful to post here for others to know about in case they ran into the same problem I did. So here’s the code that worked for me, hopefully it’ll work for you too.
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(”http://to.some.binary.data”);
req.Timeout = “blah”;
req.Method = “GET”;
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream reader = resp.GetResponseStream();
// you might want to set your responses content type here
System.IO.Stream r = Response.OutputStream;
int Length = 256;
Byte [] buffer = new Byte[Length];
int bytesRead = reader.Read(buffer, 0, Length);
while(bytesRead > 0){
r.Write(buffer, 0, bytesRead);
bytesRead = reader.Read(buffer, 0, Length);
}
Hope that helps.